1

From Pandas Dataframe, how to get the index of all ones at the row level?

My data frame has around a hundred columns. here is an example:

    a    b     c    d
0   1    0     1    0
1   0    0     0    1
2   1    1     0    1
3   1    1     0    0
4   1    1     1    1

The expected result is

0   a,c
1   d
2   a,b,d
3   a,b
4   a,b,c,d

I found this question on stackoverflow index of non "NaN" values in Pandas but it works at the column level

Thanks in advance.

3
  • 1
    Your question's title says something NaN, but there is no NaN in your sample. Commented Mar 20, 2020 at 12:08
  • sorry for the confusion. i just considered 0s as being NaN for me. Commented Mar 20, 2020 at 12:23
  • I corrected the title Commented Mar 20, 2020 at 15:31

2 Answers 2

1

If there are only 1 and 0 values use DataFrame.dot for matrix multiplication with columns names and separator, last remove separator with Series.str.rstrip:

df['e'] = df.dot(df.columns + ', ').str.rstrip(', ')
#if exist another values like 0,1 and compare 1
#df['e'] = df.eq(1).dot(df.columns + ', ').str.rstrip(', ')
print (df)
   a  b  c  d           e
0  1  0  1  0        a, c
1  0  0  0  1           d
2  1  1  0  1     a, b, d
3  1  1  0  0        a, b
4  1  1  1  1  a, b, c, d

Also for Series use:

s = df.dot(df.columns + ', ').str.rstrip(', ')
print (s)
0          a, c
1             d
2       a, b, d
3          a, b
4    a, b, c, d
dtype: object
Sign up to request clarification or add additional context in comments.

3 Comments

It is giving me a Memory Error results. Is there a way to go around this?
Number of columns is 152
Thanks it works now. it looks i had some issues with one of the columns. i removed that column
1

Try:

df=df.stack()
df=df.loc[df.eq(1)].reset_index(level=1).groupby(level=0).agg(', '.join)

Outputs:

      level_1
0        a, c
1           d
2     a, b, d
3        a, b
4  a, b, c, d

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.