import pandas as pd
dict_df={'user_id': {0: 10001,
1: 10001,
2: 10001,
3: 10001,
4: 10002,
5: 10002,
6: 10002,
7: 10002,
8: 10003,
9: 10003,
10: 10003,
11: 10003},
'model': {0: 'eat',
1: 'work',
2: 'walk',
3: 'sleep',
4: 'eat',
5: 'work',
6: 'walk',
7: 'sleep',
8: 'eat',
9: 'work',
10: 'walk',
11: 'sleep'},
'hour': {0: 1.0,
1: 10.0,
2: 0.5,
3: 7.0,
4: 1.5,
5: 9.0,
6: 0.1,
7: 1.2,
8: 9.0,
9: 1.0,
10: 8.0,
11: 9.0}}
df=pd.DataFrame(dict_df)
unstack()
df_tf=df.set_index(['user_id','model'])
df_tf=df_tf.unstack()
df_tf.reset_index(inplace=True)
df_tf
企业微信截图_a4dfcbeb-6b6a-401d-9eed-e58d4cef16c7.png
此时columns是多层索引,继续处理
企业微信截图_e788f6a7-58c1-4c9e-804b-1c2d3c97aacd.png
#删除0层索引
df_tf.columns=df_tf.columns.droplevel(0)
df_tf.rename(columns={'':'user_id'},inplace=True)
df_tf
企业微信截图_dbd34074-8058-4012-a6ba-8c9b4cc6b13c.png
#强制更改列名(注意顺序!!!)
df_tf.columns=['user_id','eat', 'sleep', 'walk', 'work']
df_tf
企业微信截图_9ddb95c8-8265-4a75-b6d9-cd78dad12f79.png