【问题标题】:Remove substring and merge rows in python/pandas在 python/pandas 中删除子字符串并合并行
【发布时间】:2021-05-06 10:29:49
【问题描述】:

我的 df:

   description               total      average      number
0 NFL football (white) L     49693        66       1007
1 NFL football (white) XL    79682        74       1198
2 NFL football (white) XS    84943        81       3792
3 NFL football (white) S     78371        73       3974
4 NFL football (blue) L      99482        92       3978
5 NFL football (blue) M      32192        51       3135
6 NFL football (blue XL      75343        71       2879
7 NFL football (red) XXL     84391        79       1192
8 NFL football (red) XS      34727        57       992
9 NFL football (red) L       44993        63       1562

我想要做的是删除尺寸并留下每种足球颜色的总和、平均数和总和数:

   description               total      average    number
0 NFL football (white)       292689       74       9971
1 NFL football (blue)        207017       71       9992
2 NFL football (red)         164111       66       3746

非常感谢任何建议!

【问题讨论】:

    标签: python pandas merge substring


    【解决方案1】:

    您可以groupby 重新格式化的description 字段(不修改description 的原始内容),其中重新格式化是通过空格分割完成的,并使用.str.split().str.join() 排除最后一部分。然后与.agg()聚合。

    通过四舍五入并与.round().astype()进行整数转换,进一步将输出重新格式化为所需的输出。

    (df.groupby(
                df['description'].str.split(' ').str[:-1].str.join(' ')
               )
       .agg({'total': 'sum', 'average': 'mean', 'number': 'sum'})
       .round(0)
       .astype(int)
    ).reset_index()
    

    结果:

                description   total  average  number
    0   NFL football (blue)  207017       71    9992
    1    NFL football (red)  164111       66    3746
    2  NFL football (white)  292689       74    9971
    

    【讨论】:

      【解决方案2】:

      替换有效,但您也可以使用 rsplit 删除描述中的最后一个单词,然后执行 groupby:

      df.description = df.description.apply(lambda x: x.rsplit(' ',1)[0])
      
      df.groupby(by='description')[['total', 'number']].sum() 
      

      【讨论】:

        猜你喜欢
        • 2018-01-22
        • 2018-07-22
        • 1970-01-01
        • 2021-05-19
        • 1970-01-01
        • 1970-01-01
        • 2021-05-02
        • 2017-12-03
        • 1970-01-01
        相关资源
        最近更新 更多