【问题标题】:exclude certain columns of a data set in a for loop在 for 循环中排除数据集的某些列
【发布时间】:2019-02-15 17:31:45
【问题描述】:

我目前正在尝试对我的数据框中的某些列进行计算,这是我的数据框中所有列的列表。

>>> list(df)
['Time', 'England Apples', 'England Oranges', 'England Pears', 'England Apricots', 'England Watermelons', 'COAL', 'England Price', 'revenue', 'roll_rev_sum', 'roll_qty_sum']

但是在我的 for 循环中,我不想选择 time 变量,所以我这样做:

for col in df.columns[1:-1]:

这很好用,但是现在我也不想在我的计算中包含 England Price,换句话说,我不希望它成为我的 for 循环中的 cols 之一。

我怎样才能做到这一点?

谢谢

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    您可以按名称删除一列(甚至更多):

    for col in df.columns[1:-1].drop(['England Price']):
       print(col)
    

    【讨论】:

      【解决方案2】:

      要获取所需列的列表,您可以这样做

      new_cols = [col for col in df.columns if col not in ['Time', 'England Price']]
      

      【讨论】:

        【解决方案3】:

        以上两者都缺少一些东西

        for cols in df.drop(['Times','England Price'],axis=1):
              print(cols)
        

        这样就可以了

        【讨论】:

          猜你喜欢
          • 2021-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-28
          • 2020-01-09
          • 1970-01-01
          相关资源
          最近更新 更多