繁体   English   中英

您如何在 Pandas 中使用条件、聚合和串联“旋转”?

[英]How do you “pivot” using conditions, aggregation, and concatenation in Pandas?

我有一个 dataframe 格式如下:

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

我需要把它变成一个 dataframe 像这样:

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 和聚合上的一些帖子,但将其翻译成这个用例让我不知所措。 非常感谢任何帮助或指示。

干杯!

使用GroupBy.aggjoin ,通过拆分创建列F并传递给DataFrame.pivot_table ,最后通过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  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM