Home > Net >  How to transform a dataframe with boolean values to a set of sequences?
How to transform a dataframe with boolean values to a set of sequences?

Time:12-15

Hi I have a dataframe with boolean values:

enter image description here

And I want to transform it into another dataframe:

enter image description here

a, b and c are the columns of the first dataframe.

CodePudding user response:

Use GroupBy.cumcount, reshape by DataFrame.melt, filter only Trues 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
  • Related