0

I have a dataset, df, where I would like to pivot the data so that the row values become columns.

Data

id  Date    consumed    available       
aa  q122    727.2       272.8       
aa  q222    975.7       24.3        
bb  q122    0           1000        
bb  q222    117.3       882.7       
                    
                    

Desired

id      q122_consumed   q122_available  q222_consumed   q222_available  
aa      727.2           272.2           975.7           24.3    
bb      0               1000            117.3           882.7   

Doing

out = df[['id', 'Date']].join(
        df.assign(consumed=df['consumed'],
                  available=df['available'])
          .groupby('id')[['consumed', 'available']].cumsum()
    ).pivot('id', 'Date', ['consumed', 'available'])

out.columns = out.columns.to_flat_index().map('_'.join)

However, I am not getting the desired output. Any suggestion is appreciated.

Lynn
  • 4,292
  • 5
  • 21
  • 44

1 Answers1

2

Use pivot method:

df.pivot(index="id", columns="Date", values=["consumed", "available"])

# output
     consumed        available
Date     q122   q222      q122   q222
id
aa      727.2  975.7     272.8   24.3
bb        0.0  117.3    1000.0  882.7
Pav3k
  • 869
  • 4
  • 10