【问题标题】:Dropping a number of columns in a pandas DataFrame on one line将 pandas DataFrame 中的多列放在一行上
【发布时间】:2018-02-02 06:16:07
【问题描述】:

您好,我有一个看起来像这样的 pandas DataFrame:

    Product_Code  W0  W1  W2  W3  W4  W5  W6  W7  W8      ...        \
806         P815   0   0   1   0   0   2   1   0   0      ...         
807         P816   0   1   0   0   1   2   2   6   0      ...         
808         P817   1   0   0   0   1   1   2   1   1      ...         
809         P818   0   0   0   1   0   0   0   0   1      ...         
810         P819   0   1   0   0   0   0   0   0   0      ...         

     Normalized 42  Normalized 43  Normalized 44  Normalized 45  \
806           0.00           0.33           0.33           0.00   
807           0.43           0.43           0.57           0.29   
808           0.50           0.00           0.00           0.50   
809           0.00           0.00           0.00           0.50   
810           0.00           0.00           0.00           0.00   

但实际上我不需要这些列,我只需要 W0 和 W4,所以我想删除所有这些列,所以这是我尝试的:

raw_data = [ raw_data.drop( [i], 1, inplace = True )  for i in raw_data if i is not 'W0' and i is not  'W4'  ]

半小时后,我发现由于某种原因 != 不起作用字符串 and I was wondering why? 所以我有一个稳定的解决方案:

#WORKS !!!!
# for i in raw_data:
#     if i != 'W0' and i != 'W4':
#         raw_data.drop( [i], 1, inplace = True )  

但我一点也不喜欢它,我评论了它,因为它占用很多空间而且它不漂亮,我想让表达式工作的单行循环,是否可能,问题是那:

  raw_data = [ raw_data.drop( [i], 1, inplace = True )  for i in raw_data if i != 'W0' and i != 'W4'  ]

尝试将DataFrame转为列表,应该怎么做?

【问题讨论】:

    标签: python pandas scikit-learn sklearn-pandas


    【解决方案1】:

    你可以使用:

    raw_data.drop([i for i in raw_data if i is not 'W0' and i is not  'W4'], 
                   axis=1, inplace=True)
    

    这回答了问题,但您陈述的条件没有意义。你提出的条件是if i is not 'W0' and i is not 'W4',这将永远是真的。您可能需要再次查看条件。

    【讨论】:

    • 是的,我以为!=相当于is not
    • 嗯它是。您可能正在寻找 or 运算符而不是 and
    • 不是不是它不适用于is not,我正在寻找,因为if i is W0 => i is not w0(False) and i is not W4(True) => 表达式是False => 我们不会删除该列
    • @ClockSlave 绝对不是。 !=is not 非常不同。
    • @cᴏʟᴅsᴘᴇᴇᴅ,哇一年多了还是不知道!
    【解决方案2】:

    这应该可行:

     raw_data = pd.DataFrame(raw_data, index=your_index, columns=['W0', 'W4'])
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2016-11-17
      • 1970-01-01
      • 2014-01-01
      • 2016-11-07
      • 1970-01-01
      • 2022-01-03
      • 2023-02-05
      • 1970-01-01
      相关资源
      最近更新 更多