Pandas Map 0/1 Data Frame Entries To Column Names
I have a data frame in pandas with entries that are either 0 or 1. I would like to reduce this to a single list of strings that are the result from concatentating column names wher
Solution 1:
convert the dtype of the df to a bool
, then call apply
and use the boolean mask to mask the columns, you need to pass param axis=1
to apply
the column mask row-wise:
In [47]:
df.astype(bool).apply(lambda x: ','.join(df.columns[x]), axis=1)
Out[47]:
0 V2,V3
1 V1,V2
2
dtype: object
Your code my_df.apply(lambda x: colnames[x])
won't work because firstly when calling apply
on a df without specifying the axis
will call the lambda on each column in turn, secondly the 1/0
will interpret this as an index value rather than a boolean flag.
Post a Comment for "Pandas Map 0/1 Data Frame Entries To Column Names"