【问题标题】:pandas create new column based on grouping [duplicate]熊猫根据分组创建新列[重复]
【发布时间】:2019-01-23 04:02:37
【问题描述】:

我有一个如下所示的 pandas 数据框。

df =     index| date | amount| type|
           0  | 2015 | 1000  | A   |
           1  | 2015 | 100   | B   |
           2  | 2016 | 3500  | A   |
           3  | 2017 | 150   | C   |

我想根据类型生成一个带有新列的数据框。结果如下所示。

df =     index| date | A   | B   | C   
           0  | 2015 | 1000| 100 |0
           1  | 2016 | 3500| 0   |0
           2  | 2017 | 0   | 0   |150

【问题讨论】:

    标签: python python-3.x python-2.7 pandas numpy


    【解决方案1】:

    你可以试试

    ss=df.groupby(['date','type']).sum().reset_index()
    ss.pivot(index='date',columns='type',values='amount').fillna(0)
    

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2021-02-28
      • 1970-01-01
      • 2020-07-07
      • 2022-08-09
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      相关资源
      最近更新 更多