您如何在 Pandas 中使用条件、聚合和串联来“转换”?
How do you “pivot” using conditions, aggregation, and concatenation in Pandas?
我有一个格式如下的数据框:
Index Name Fruit Quantity
0 John Apple Red 10
1 John Apple Green 5
2 John Orange Cali 12
3 Jane Apple Red 10
4 Jane Apple Green 5
5 Jane Orange Cali 18
6 Jane Orange Spain 2
我需要将它变成这样的数据框:
Index Name All Fruits Apples Total Oranges Total
0 John Apple Red, Apple Green, Orange Cali 15 12
1 Jane Apple Red, Apple Green, Orange Cali, Orange Spain 15 20
问题是我该怎么做?我已经查看了 groupby 文档以及许多关于数据透视和聚合的帖子,但不知何故将其转化为这个用例让我不知所措。非常感谢任何帮助或指点。
干杯!
使用GroupBy.agg
with join
, create column F
by split and pass to DataFrame.pivot_table
, last join together by DataFrame.join
:
df1 = df.groupby('Name', sort=False)['Fruit'].agg(', '.join)
df2 = (df.assign(F = df['Fruit'].str.split().str[0])
.pivot_table(index='Name',
columns='F',
values='Quantity',
aggfunc='sum')
.add_suffix(' Total'))
df3 = df1.to_frame('All Fruits').join(df2).reset_index()
print (df3)
Name All Fruits Apple Total \
0 John Apple Red, Apple Green, Orange Cali 15
1 Jane Apple Red, Apple Green, Orange Cali, Orange Spain 15
Orange Total
0 12
1 20
我有一个格式如下的数据框:
Index Name Fruit Quantity
0 John Apple Red 10
1 John Apple Green 5
2 John Orange Cali 12
3 Jane Apple Red 10
4 Jane Apple Green 5
5 Jane Orange Cali 18
6 Jane Orange Spain 2
我需要将它变成这样的数据框:
Index Name All Fruits Apples Total Oranges Total
0 John Apple Red, Apple Green, Orange Cali 15 12
1 Jane Apple Red, Apple Green, Orange Cali, Orange Spain 15 20
问题是我该怎么做?我已经查看了 groupby 文档以及许多关于数据透视和聚合的帖子,但不知何故将其转化为这个用例让我不知所措。非常感谢任何帮助或指点。
干杯!
使用GroupBy.agg
with join
, create column F
by split and pass to DataFrame.pivot_table
, last join together by DataFrame.join
:
df1 = df.groupby('Name', sort=False)['Fruit'].agg(', '.join)
df2 = (df.assign(F = df['Fruit'].str.split().str[0])
.pivot_table(index='Name',
columns='F',
values='Quantity',
aggfunc='sum')
.add_suffix(' Total'))
df3 = df1.to_frame('All Fruits').join(df2).reset_index()
print (df3)
Name All Fruits Apple Total \
0 John Apple Red, Apple Green, Orange Cali 15
1 Jane Apple Red, Apple Green, Orange Cali, Orange Spain 15
Orange Total
0 12
1 20