Selecting columns with condition on Pandas DataFrame
To apply one condition to the whole dataframe
df[(df == 'something1').any(axis=1)]
You can use all
with boolean indexing
:
print ((df == 'something1').all(1))
0 True
1 False
2 True
3 False
4 False
dtype: bool
print (df[(df == 'something1').all(1)])
col1 col2
0 something1 something1
2 something1 something1
EDIT:
If need select only some columns you can use isin
with boolean indexing
for selecting desired columns
and then use subset
- df[cols]
:
print (df)
col1 col2 col3
0 something1 something1 a
1 something2 something3 s
2 something1 something1 r
3 something2 something3 a
4 something1 something2 a
cols = df.columns[df.columns.isin(['col1','col2'])]
print (cols)
Index(['col1', 'col2'], dtype='object')
print (df[(df[cols] == 'something1').all(1)])
col1 col2 col3
0 something1 something1 a
2 something1 something1 r
Why not:
df[(df.col1 == 'something1') | (df.col2 == 'something1')]
outputs:
col1 col2
0 something1 something1
2 something1 something1
4 something1 something2