+1 vote
in Programming Languages by (60.0k points)
I want to find the indices of all columns of a DataFrame that contain only 0s for all rows. How can I do it?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

You can use Pandas DataFrame functions all() or any() with index to find columns with all 0s.

Here are some approaches:

>>> import pandas as pd

>>> df = pd.DataFrame({'A':[1,2,3,4], 'B':[0,0,0,0], 'C':[10,20,30,40], 'D':[0,0,0,0]})

>>> df

   A  B   C  D

0  1  0  10  0

1  2  0  20  0

2  3  0  30  0

3  4  0  40  0

Approach 1

>>> np.where((df==0).all(axis=0).to_numpy())[0]

array([1, 3])

Approach 2

>>> df.index[~df.any(axis=0)]

Index([1, 3], dtype='int64')

Approach 3

>>> df.index[(df==0).all(axis=0)]

Index([1, 3], dtype='int64')


...