【问题标题】:Group by 2 columns and create an orderID based on this grouping按 2 列分组并基于此分组创建 orderID
【发布时间】:2021-05-21 14:39:34
【问题描述】:

我有一个数据框 df,我将在其中创建基于 2 列的不同订单 ID:季度和位置。

数据

location    type    quarter 
ny          aa      1   
ny          aa      1   
ny          bb      1   
ny          aa      2   
ny          aa      2   
ny          bb      2   
ca          cc      3   
ca          aa      3   

希望

location    type    quarter Id
ny          aa      1       aa01
ny          aa      1       aa02
ny          bb      1       bb01
ny          aa      2       aa01
ny          aa      2       aa02
ny          bb      2       bb01
ca          cc      3       cc01
ca          aa      3       aa01

Order Id 采用类型并根据该类型在季度和位置中的数量在其末尾添加一个数值。

正在做

我打算这样做:

df['type']     = df.groupby('type').ngroup()
df['location'] = df.groupby('location').ngroup()

这将对列进行分组,但这是单独的解决方案,我希望维护所有原始列并将其保存在我的数据框中。

感谢任何建议。我还在研究中

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    根据您的预期输出,必须使用 GroupBy.cumcount 按 3 列分组,添加 1 因为计数器由 0 开始,转换为字符串并添加 0 以得到最少 2 位数字,由 Series.str.zfill 添加到 @ 987654328@专栏:

    s = df.groupby(['location','type','quarter']).cumcount().add(1).astype(str).str.zfill(2)
    df['Id'] = df['type'] + s
    print (df)
      location type  quarter    Id
    0       ny   aa        1  aa01
    1       ny   aa        1  aa02
    2       ny   bb        1  bb01
    3       ny   aa        2  aa01
    4       ny   aa        2  aa02
    5       ny   bb        2  bb01
    6       ca   cc        3  cc01
    7       ca   aa        3  aa01
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 2015-03-10
      相关资源
      最近更新 更多