J-H
J-H

Reputation: 1869

Pandas Dataframe Filtering Columns and return column name

How can i filter a Pandas DataFrame which looks like this:

Head   Cat1   Cat2   Cat3
"A"     0      0      1
"B"     1      0      1

So that it returns for every row the Category-Column-Names if not 0

For example

"A"   "Cat3"
"B"   "Cat1" "Cat3"

I have no idea how to solve this and i deeply appreciate every help

Upvotes: 1

Views: 944

Answers (1)

EdChum
EdChum

Reputation: 394031

You can filter the columns first to get the cols of interest and then call apply and use the boolean mask to mask the cols:

In [18]:
cat_cols = df.columns[df.columns.str.contains('Cat')]
df[cat_cols].apply(lambda row: ', '.join(cat_cols[row == 1]), axis=1)

Out[18]:
0          Cat3
1    Cat1, Cat3
dtype: object

Also possible to retrieve the columns by accessing the .index attribute:

df[cat_cols].apply(lambda row: ', '.join(row.index[row == 1]), axis=1)

Upvotes: 1

Related Questions