pandas: print names of columns with nonzero elements in row?

Viewed 760

I have a DataFrame with a bunch of columns where the values are zero or 1. For example,

import numpy as np
import pandas as pd
df = pd.DataFrame(np.array([[0,1,0,1],[1,1,0,0]]), columns=['a','b','c','d'])
df

    a   b   c   d
0   0   1   0   1
1   1   1   0   0

In a given row (say 0), I want to print the names of the nonzero columns. I tried using

df.iloc[0].nonzero()

but instead of getting 'b', 'd' (or even [1, 3] as nonzero() is supposed to return indices), I get

AttributeError: 'Series' object has no attribute 'nonzero'

(Edit: forget this line: I thought nonzero() was an method of Series.)

How can I get the column names as desired?

(Tried searching before asking this, but didn't find any duplicates.)

2 Answers

Try this:

df.iloc[0].loc[lambda df: df.ne(0)].index
Index(['b', 'd'], dtype='object')

According to the pandas documentation, Series.nonzero() is replaced by Series.to_numpy().nonzero().

Instead of

df.iloc[0].nonzero()

Try

df.iloc[0].to_numpy().nonzero()
Related