+1 vote
in Programming Languages by (77.2k points)
In a dataframe, there are some rows that contain only 0s. I want to find the indices of all such rows. How can I find them?

1 Answer

+2 votes
by (354k points)
selected by
 
Best answer

To find the indices of all rows in a DataFrame that contain only 0s, you can use either  DataFrame.all() or DataFrame.any() method along with boolean indexing. The all() function checks whether all elements over the given axis are True. The any() function checks whether any element over the given axis is True.

Here is an example using all() and any() functions:

>>> import pandas as pd
>>> data = {'A': [0, 1, 0, 0, 1], 'B': [0, 0, 0, 0, 1], 'C': [1, 0, 0, 0, 1]}
>>> df = pd.DataFrame(data)
>>> df
   A  B  C
0  0  0  1
1  1  0  0
2  0  0  0
3  0  0  0
4  1  1  1
>>> df.index[~df.any(axis=1)]
Index([2, 3], dtype='int64')

>>> df.index[(df == 0).all(axis=1)]
Index([2, 3], dtype='int64')


...