我有长格式的数据,正在尝试重新调整为宽格式,但似乎没有直接的方法可以使用 melt/stack/unstack:
Salesman Height product price
Knut 6 bat 5
Knut 6 ball 1
Knut 6 wand 3
Steve 5 pen 2
变成:
Salesman Height product_1 price_1 product_2 price_2 product_3 price_3
Knut 6 bat 5 ball 1 wand 3
Steve 5 pen 2 NA NA NA NA
我认为 Stata 可以用 reshape 命令做这样的事情。
最佳答案
这是另一个更加充实的解决方案,取自 Chris Albon's site .
创建“长”数据框
raw_data = {'patient': [1, 1, 1, 2, 2],
'obs': [1, 2, 3, 1, 2],
'treatment': [0, 1, 0, 1, 0],
'score': [6252, 24243, 2345, 2342, 23525]}
df = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score'])
制作“宽”数据
df.pivot(index='patient', columns='obs', values='score')
关于python - Pandas 从长到宽 reshape ,通过两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798934/