【问题标题】:Python Panda problems with group by and regularexpression分组依据和正则表达式的 Python Panda 问题
【发布时间】:2022-12-05 03:00:07
【问题描述】:

像风箱一样的表格样本-

Product                       Price

P1,Luxary product              2000  

P2: Cosmetics product          1700

P1::Plastic product            600

P3/P1,Mobile phone             3300

P2:headphones                  200

P3,Trimmer                     150

P2,Camera                      2200

P2/Airpods                     250

P3;;phone case                 100

P2/P1:Mirrors                  800

Water Bottel P2 2011           60

从产品列中,我如何提取隐藏的歌曲(- P1、P2 和 P3) 有时会有多个标志,如果只提取第一个标志就可以了。 然后用价格列按他们(符号)分组并从高价打印到低价?

输出:

P2  - 5210
P3  - 3550
P1  - 2600

【问题讨论】:

    标签: python pandas regex group-by


    【解决方案1】:

    假设您的“隐藏标志”总是包含两个字符,只需创建包含这些前缀的新列:

    df['Prefix'] = df['Product'].str[:2]
    

    然后您可以按前缀分组:

    df.groupby('Prefix').sum()
    

    【讨论】:

      【解决方案2】:

      这是一个使用 pandas.Series.str.extract 的命题:

      out = (
              df
                .assign(Signs= df["Product"].str.extract("(Pd)", expand=False))
                .groupby("Signs", as_index=False)["Price"].sum()
             )
      

      # 输出 :

      print(out)
      
        Signs  Price
      0    P1   2600
      1    P2   5210
      2    P3   3550
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 2010-11-22
        • 1970-01-01
        • 2010-10-20
        • 2014-11-29
        相关资源
        最近更新 更多