我有一个叫做df的Pandas (下面是简短的片段)
deathtype height deaths
0 AMS 4900 1
1 AMS 5150 1
2 AMS 5300 1
3 Avalanche 5350 14
4 Avalanche 5600 4
5 Avalanche 5700 1
6 Avalanche 5800 17
7 Unexplained 8500 1
8 Unexplained 8560 1我试图将数据重塑为以下内容;
deaths 1 4 14 17
deathtype
AMS 4900,5150,5300 0 0 0
Avalanche 5700 5600 5350 5800
Unexplained 8500, 8560 0 0 0我知道pivot_table无法做到这一点,因为aggfunc使用均值表示重复值,这意味着对于所有的deaths值1,平均值都将被记录下来。一个pivot_table给了我以下内容;
df.pivot_table(index='deathtype', columns='deaths', values='height', fill_value='0')
deaths 1 4 14 17
deathtype
AMS 5116.666667 0 0 0
Avalanche 5700.000000 5600 5350 5800
Unexplained 8530.000000 0 0 0我在找一些关于如何做这件事的建议。在这里,看起来pivot_table不是正确的方法。有人能给我一些指点吗。
发布于 2018-06-10 12:16:12
将groupby与join聚合一起使用,然后通过unstack进行重组
d = lambda x: ', '.join(x.astype(str))
df = df.groupby(['deathtype', 'deaths'])['height'].agg(d).unstack(fill_value='0')
print (df)
deaths 1 4 14 17
deathtype
AMS 4900, 5150, 5300 0 0 0
Avalanche 5700 5600 5350 5800
Unexplained 8500, 8560 0 0 0细节
print (df.groupby(['deathtype', 'deaths'])['height'].agg(lambda x: ', '.join(x.astype(str))))
deathtype deaths
AMS 1 4900, 5150, 5300
Avalanche 1 5700
4 5600
14 5350
17 5800
Unexplained 1 8500, 8560
Name: height, dtype: object另一种使用pivot_table的解决方案
df = df.pivot_table(index='deathtype',
columns='deaths',
values='height',
fill_value='0',
aggfunc=lambda x: ', '.join(x.astype(str)))https://stackoverflow.com/questions/50783545
复制相似问题