Reputation: 419
i am working with pandas with dataframe like bleow
area date m1 m2
IDC1 02/01/2017 400 80
IDC1 03/01/2017 400 70
IDC2 02/01/2017 410 204
IDC2 03/01/2017 400 214
i wnat to transform it to below, i have been seen the pd.melt,but still not working.
area date 02/01/2017 03/01/2017
IDC1 m1 400 400
IDC1 m2 80 70
IDC2 m1 410 400
IDC2 m2 204 214
Upvotes: 1
Views: 39
Reputation: 863226
Use set_index
with stack
and unstack
:
df = (df.set_index(['area', 'date'])
.stack()
.unstack(1, fill_value=0)
.rename_axis(('area','date'))
.rename_axis(None, 1)
.reset_index())
print (df)
area date 02/01/2017 03/01/2017
0 IDC1 m1 400 400
1 IDC1 m2 80 70
2 IDC2 m1 410 400
3 IDC2 m2 204 214
Upvotes: 1