【发布时间】:2018-06-10 12:11:07
【问题描述】:
我有一个名为 df 的 Pandas DF(下面是简短的 sn-p)
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 使用重复值的平均值,这意味着对于所有为 1 的 deaths 值,均值将被记录。 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 不是正确的方法。谁能指点一下。
【问题讨论】:
标签: python pandas dataframe reshape