【问题标题】:how i can delete no needed columns from Dataframe with pandas [duplicate]我如何使用 pandas 从 Dataframe 中删除不需要的列 [重复]
【发布时间】:2021-04-14 11:20:26
【问题描述】:

这是我的代码,我只需要处理最后 4 列“开盘价、最高价、最低价、收盘价”

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('bmh')
data = json.load(open('GBPUSD_D1.json'))
df = pd.DataFrame(data=data, index=data["time"], columns=data)
print(df.head(5))```


output :
```         ver  dataId     terminal             company        server  ...     open     high      low    close  volume
3682080    3     NaN  forexsb.com  Forex Software Ltd  Premium Data  ...  1.95805  1.96417  1.95765  1.96332  146179
3683520    3     NaN  forexsb.com  Forex Software Ltd  Premium Data  ...  1.96330  1.97418  1.96040  1.97295  157568
3684960    3     NaN  forexsb.com  Forex Software Ltd  Premium Data  ...  1.97301  1.97490  1.94814  1.95169  147924
3686400    3     NaN  forexsb.com  Forex Software Ltd  Premium Data  ...  1.95165  1.95296  1.93980  1.94258  148462
3687840    3     NaN  forexsb.com  Forex Software Ltd  Premium Data  ...  1.94251  1.94316  1.92633  1.92900  142467

[5 rows x 32 columns]```

【问题讨论】:

  • 使用 'dataframe.drop()' 或仅保留您需要的列进行复制。

标签: python-3.x pandas dataframe


【解决方案1】:
df = df[["open", "high", "low", "close"]]

【讨论】:

    【解决方案2】:

    试试

    df = df[["open", "high", "low", "close"]] # only select four columns
    

    df = df.drop(df.iloc[:, 0:-5], axis=1) # delete all except last 5 columns
    df = df.drop(df.iloc[:, -1], axis=1) # delete last column
    

    inplace=True 可以在drop 调用中使用以避免复制:

    df.drop(df.iloc[:, 0:-5], axis=1, inplace=True)
    df.drop(df.iloc[:, -1], axis=1, inplace=True)
    

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2012-09-25
      • 1970-01-01
      • 2020-12-17
      • 2018-05-29
      • 2018-05-01
      • 2020-02-10
      相关资源
      最近更新 更多