gpt4 book ai didi

python - Pandas 由长到宽的 reshape ,通过两个变量

转载 作者:行者123 更新时间:2023-12-02 01:15:05 33 4
gpt4 key购买 nike

我有长格式的数据,并且正在尝试将其 reshape 为宽格式,但似乎没有一种简单的方法可以使用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/55252251/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com