你是怎么做的“;枢轴&x201D;在Pandas中使用条件、聚合和连接?

你是怎么做的“;枢轴&x201D;在Pandas中使用条件、聚合和连接?,pandas,pivot,conditional-statements,concatenation,aggregation,Pandas,Pivot,Conditional Statements,Concatenation,Aggregation,我有如下格式的数据帧: 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

我有如下格式的数据帧:

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文档以及许多关于pivot和aggregation的文章,但不知何故,将它们转换成这个用例让我不知所措。非常感谢任何帮助或指点

干杯

join
一起使用,通过拆分和传递到创建列
F
,最后通过以下方式连接在一起:


谢谢如果我们在原始数据框中再添加两行,为John和Jane添加另一种水果,比如香蕉,我们不希望将其数量包含在总计列中,那么如何设置求和函数来考虑这种情况?@Zaphod我认为最好的方法是提出新问题。
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