【问题标题】:Add new column indicating count in a pandas dataframe在熊猫数据框中添加指示计数的新列
【发布时间】:2020-10-05 07:00:56
【问题描述】:

我有一个包含一些复制行的数据框

item h2 h3  h4
----------------
foo  v1 ... ...
foo  v2 ... ...
foo  v1 ... ...
foo  v2 ... ...
foo  v1 ... ...
foo  v2 ... ...
foo  v1 ... ...
foo  v2 ... ...
bar  v5 ... ...
bar  v6 ... ...
bar  v7 ... ...
bar  v5 ... ...
bar  v6 ... ...
bar  v7 ... ...

我的目标是在此数据框中添加一列 (new_id),以指示重复块的递增计数(块是一组具有相同 item 名称的行),前缀为 @987654324 中的值@column(如果有帮助,复制的块将是连续的)

item h2 h3  h4   new_id
-----------------------
foo  v1 ... ...  foo1
foo  v2 ... ...  foo1
foo  v1 ... ...  foo2
foo  v2 ... ...  foo2
foo  v1 ... ...  foo3
foo  v2 ... ...  foo3
foo  v1 ... ...  foo4
foo  v2 ... ...  foo4
bar  v5 ... ...  bar1
bar  v6 ... ...  bar1
bar  v7 ... ...  bar1
bar  v5 ... ...  bar2
bar  v6 ... ...  bar2
bar  v7 ... ...  bar2

关于如何做到这一点的建议?

【问题讨论】:

    标签: python pandas pyspark


    【解决方案1】:

    使用str.cat() 将列itemh2 中每个组的累积计数连接起来。显然累积计数从零开始,偏移1

    df.item.str.cat((df.groupby('h2').cumcount()+1).astype(str),sep='')
    
    
    
      item  h2   h3   h4 new_id
    0   foo  v1  ...  ...   foo1
    1   foo  v2  ...  ...   foo1
    2   foo  v1  ...  ...   foo2
    3   foo  v2  ...  ...   foo2
    4   foo  v1  ...  ...   foo3
    5   foo  v2  ...  ...   foo3
    6   foo  v1  ...  ...   foo4
    7   foo  v2  ...  ...   foo4
    8   bar  v5  ...  ...   bar1
    9   bar  v6  ...  ...   bar1
    10  bar  v7  ...  ...   bar1
    11  bar  v5  ...  ...   bar2
    12  bar  v6  ...  ...   bar2
    13  bar  v7  ...  ...   bar2
    

    【讨论】:

      【解决方案2】:

      itemh2 两列中使用GroupBy.cumcount

      df['new_id'] = df['item'] + '_' + df.groupby(['item','h2']).cumcount().add(1).astype(str)
      print (df)
         item  h2   h3   h4 new_id
      0   foo  v1  ...  ...  foo_1
      1   foo  v2  ...  ...  foo_1
      2   foo  v1  ...  ...  foo_2
      3   foo  v2  ...  ...  foo_2
      4   foo  v1  ...  ...  foo_3
      5   foo  v2  ...  ...  foo_3
      6   foo  v1  ...  ...  foo_4
      7   foo  v2  ...  ...  foo_4
      8   bar  v5  ...  ...  bar_1
      9   bar  v6  ...  ...  bar_1
      10  bar  v7  ...  ...  bar_1
      11  bar  v5  ...  ...  bar_2
      12  bar  v6  ...  ...  bar_2
      13  bar  v7  ...  ...  bar_2
      

      【讨论】:

      • 感谢您的快速回答!我刚刚更新了我的问题以澄清示例.. 很抱歉造成混淆。你能再看一遍并更新你的答案吗?非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2017-08-21
      • 2012-09-04
      • 2017-01-14
      • 2018-12-01
      相关资源
      最近更新 更多