1

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.