anarchy
anarchy

Reputation: 5204

Filter pandas columns based on multiple row condition

This is an extension to my earlier question.

Filter pandas columns based on row condition

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

I want to filter the columns where row3 is true,

and i want to filter the columns where row2 is >3

So in this example only column x3 should appear.

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?

Upvotes: 1

Views: 83

Answers (1)

Pygirl
Pygirl

Reputation: 13349

It should be:

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

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:

x3

df.loc[:,x]

Upvotes: 1

Related Questions