Get index of Pandas Dataframe where some columns are zero

Viewed 29

This is probably very simple but I can't seem to make it work for some reason. Let's say I have a dataframe:

    A   B   C   D   E  ... Z
1   0   2   3   0   5  ... 0
2   5   0   0   0   4  ... 1
3   0   0   3   0   10 ... 12
4   4   0   0   0   0  ... 0

and a list col that has certain columns of the dataframe

How can I return a list of the index of the rows for which columns of col are all 0? For example if col = ['B', 'C', 'D'] I would like it to return idx = [2, 4]

I tried doing idx = df.index[df.loc[col].sum() == 0].tolist() but I get a ValueError even though all the columns exist in the dataframe.

Any help is much appreciated!

1 Answers

You can use all. sum is not a good option as it's probably more expensive to compute the sum and you would potentially have false positives if there are negative values:

col = ['B', 'C', 'D']

df.index[df[col].eq(0).all(axis=1)].to_list()

output: [2, 4]

Related