根据多行条件过滤熊猫列

时间:2021-02-24 19:30:05

标签: python pandas filter

这是我之前问题的延伸。

Filter pandas columns based on row condition

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

这是我的数据

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

df.loc[[:,df.loc['row3']==True] 如果我只想过滤 row3

True 条件

我想过滤 row3true 的列,

and 我想过滤 row2>3

的列

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

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

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

应该是:

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

x:

x1    False
x2    False
x3     True
dtype: bool

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

x[x].index[0]

输出:

x3

df.loc[:,x]