Hi I have a dataframe with boolean values:
And I want to transform it into another dataframe:
a, b and c are the columns of the first dataframe.
CodePudding user response:
Use GroupBy.cumcount
, reshape by DataFrame.melt
, filter only True
s and pivot in DataFrame.pivot_table
:
df['g'] = df.groupby(level=0).cumcount()
df = df.melt('g', ignore_index=False)
df = (df[df['value']]
.reset_index()
.pivot_table(index='index', columns='g', values='variable', aggfunc=' '.join)
.rename_axis(index=None, columns=None))
print (df)
0 1 2
1 b c b c NaN
2 b NaN NaN
3 a b c a c a