【问题标题】:Filter pandas columns based on multiple row condition根据多行条件过滤熊猫列
【发布时间】:2021-02-24 19:30:05
【问题描述】:

这是对我之前的问题的扩展。

Filter pandas columns based on row condition

现在我想有多个条件来过滤列。

这是我的数据

        x1    x2   x3 ....
row1    12   3.4    5  ...
row2     1     3    4 ...
row3  True False True ...
...

如果我只想过滤Truerow3 条件,df.loc[[:,df.loc['row3']==True] 可以工作

我想过滤row3true 的列,

and 我想过滤row2>3 的列

所以在这个例子中只有 x3 列应该出现。

我尝试了以下代码,但出现错误。我也尝试添加括号。

df.loc[:,df.loc['row3']==True & :,df.loc['row2']>3]

有什么想法吗?

【问题讨论】:

    标签: python pandas filter


    【解决方案1】:

    应该是:

    x = (pd.to_numeric(df.loc['row2'],'coerce').gt(3)) & (df.loc['row3']=='True')
    

    x:

    x1    False
    x2    False
    x3     True
    dtype: bool
    

    然后您可以轻松地应用过滤器来获取值为 true 的列。

    x[x].index[0]
    

    输出:

    x3
    

    df.loc[:,x]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2016-08-31
      • 2021-12-01
      • 2013-09-06
      • 2017-10-03
      • 2023-01-11
      • 2018-08-09
      相关资源
      最近更新 更多