【问题标题】:How to group merge columns based on one row identifier with pandas?如何根据一个行标识符与熊猫对合并列进行分组?
【发布时间】:2020-11-27 04:14:16
【问题描述】:

我有一个数据集,其中有很多针对单个位置的条目。我正在尝试找到一种方法来总结所有这些条目而不影响任何其他列。因此,以防万一我解释得不够好,我想使用这样的数据集:

Locations   Cyclists   maleRunners   femaleRunners   maleCyclists   femaleCyclists
Bedford     10         12            14              17             27
Bedford     11         40            34              9              1
Bedford     7          1             2               3              3
Leeds       1          1             2               0              0
Leeds       20         13            6               1              1
Bath        101        20            33              41             3
Bath        11         2             3               1              0

然后把它变成这样的:

Locations   Cyclists   maleRunners   femaleRunners   maleCyclists   femaleCyclists
Bedford     28         53            50              29             31
Leeds       21         33            39              1              1
Bath        111        22            36              42             3

现在,我已经读到 groupby 应该以某种方式工作,但据我了解,group by 会将其更改为 2 列,我不想制作数百个 2 列然后将其全部合并。当然有更简单的方法来做到这一点?

【问题讨论】:

    标签: pandas merge dataset


    【解决方案1】:

    iiuc,groupby sum将为您工作:

    df.groupby('Locations',as_index=False,sort=False).sum()
    

    输出:

      Locations  Cyclists  maleRunners  femaleRunners  maleCyclists  femaleCyclists
    0   Bedford        28           53             50            29              31
    1     Leeds        21           14              8             1               1
    2      Bath       112           22             36            42               3
    

    【讨论】:

      【解决方案2】:

      数据透视表应该适合你。

      new_df = pd.pivot_table(df, values=['Cyclists', 'maleRunners', 'femalRunners', 
                                           'maleCyclists','femaleCyclists'],index='Locations', aggfunc=np.sum)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-23
        • 2020-04-09
        • 2013-07-30
        • 1970-01-01
        • 2022-01-25
        • 2021-05-14
        • 2021-11-02
        相关资源
        最近更新 更多