简体   繁体   English

根据多行条件过滤 pandas 列

[英]Filter pandas columns based on multiple row condition

This is an extension to my earlier question.这是对我之前的问题的扩展。

Filter pandas columns based on row condition 根据行条件过滤 pandas 列

Now i want to have multiple conditions to filter columns.现在我想有多个条件来过滤列。

Here is my data这是我的数据

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

df.loc[[:,df.loc['row3']==True] works if I just want to filter the row3 condition of True如果我只想过滤Truerow3条件, df.loc[[:,df.loc['row3']==True]有效

I want to filter the columns where row3 is true ,我想过滤row3true的列,

and i want to filter the columns where row2 is >3我想过滤row2 >3 and

So in this example only column x3 should appear.所以在这个例子中,只有 x3 列应该出现。

I tried the following code but I get an error.我尝试了以下代码,但出现错误。 I also tried adding brackets.我也尝试添加括号。

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

Any ideas?有任何想法吗?

It should be:它应该是:

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

x: X:

x1    False
x2    False
x3     True
dtype: bool

then you can easily apply filter to get the column where the value is true.那么您可以轻松地应用过滤器来获取值为真的列。

x[x].index[0]

output: output:

x3

df.loc[:,x]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM