Suppose I have a pandas DataFrame like this
JavaScript
x
5
1
name col1 col2 col3
2
0 AAA 1 0 2
3
1 BBB 2 1 2
4
2 CCC 0 0 2
5
I want (a) the names of any columns that contain a value of 2
anywhere in the column (i.e., col1
, col3
), and (b) the names of any columns that contain only values of 2
(i.e., col3
).
I understand how to use DataFrame.any()
and DataFrame.all()
to select rows in a DataFrame where a value appears in any or all columns, but I’m trying to find COLUMNS where a value appears in (a) any or (b) all rows.
Advertisement
Answer
You can do what you described with columns:
JavaScript
1
6
1
df.columns[df.eq(2).any()]
2
# Index(['col1', 'col3'], dtype='object')
3
4
df.columns[df.eq(2).all()]
5
# Index(['col3'], dtype='object')
6