如何按大熊猫中相似的行分组

时间:2019-06-01 20:25:33

标签: python pandas

我在数据帧上应用了groupby

  

df.groupby('Category')。sum()

之后的结果数据帧如下所示

               height      weight 
General  42.849980  157.500553    
GENERAL  49.607315  177.340407 
Genera  56.293531  171.524640  
CategoryA  48.421077  144.251986  
CategoryB  48.421077  144.251986
CategoryC  48.421077  144.251986 

我需要将General,GENERAL和Genera分组为一行,其结果应类似于

General    123.849980  300.500553    
CategoryA  48.421077  144.251986  
CategoryB  48.421077  144.251986
CategoryC  48.421077  144.251986 

我该怎么做?

编辑:使用正则表达式获得解决方案。 如果需要将General,GENERAL,Genera和CategoryA归为一个组,有什么办法?

2 个答案:

答案 0 :(得分:3)

假设您要分组的类别在索引中,则可以执行以下操作:

import re

result = (
    df
    .groupby(df.index.str.replace("genera.*", "General", flags=re.IGNORECASE))
    .sum()
)

答案 1 :(得分:0)

您可以在进行groupby之前重命名一般列,如下所示:

df = pd.DataFrame({'name': ['General', 'General', 'General', 'GENERAL', 'GENERAL'], 'height': [1,2,3,4,5]})
df['name'].replace({'GENERAL' : 'General'}, inplace =True)
df.groupby(['name']).sum()

退出:

name    height
General 15
相关问题