Reputation: 85
I would like to fetch the column indices given that they meet a certain condition.
For instance, I would like to fetch the indices of all columns that contain 0. In this case, it would be [0,1] --> (column A and column B).
df = {'A': [0,1,2,3,4,5],
'B': [3,4,0,5,6,5],
'C': [1,2,3,4,5,6],
'D': [7,8,9,8,7,6]}
df = pd.DataFrame(df)
Thanks!
Upvotes: 1
Views: 552
Reputation: 14949
Use np.where:
index_array = np.where(df.eq(0).any())[0] # prints array([0, 1])
index_array = np.where(~df.eq(0).any())[0] # prints array([2, 3])
In case if you need column names:
col_list = df.columns[df.eq(0).any()] # prints Index(['A', 'B'], dtype='object')
Upvotes: 3
Reputation: 18
This should help you out.
(df == 0).any(axis=1)
op:
0 True
1 False
2 True
3 False
4 False
5 False
dtype: bool
Upvotes: 0