Pandas:重塑具有重复条目的数据框
Pandas: reshaping a dataframe with duplicate entries
我有一个名为 df
的 Pandas DF(下面的简短片段)
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 在这里不是正确的方法。有没有人可以指点一下。
将 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)))
我有一个名为 df
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 在这里不是正确的方法。有没有人可以指点一下。
将 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)))