【问题标题】:How to get the 'number' of occurrence of a value in a column in another column in a pandas dataframe [duplicate]如何获取 pandas 数据框中另一列中某列值出现的“次数”[重复]
【发布时间】:2023-01-12 18:41:14
【问题描述】:

我需要在数据框中的另一列中的一列中获取特定值出现的确切“数量”。 为了简单起见,需要一个列中重复值的累计计数

考虑以下示例:

col_A col_B
test1 some1
test2 some2
test2 some3
test2 some4
test3 some5
test1 some6
test3 some7

我需要一个 col_C 来获取 col_A 值的确切出现次数 考虑以下:

col_A col_B col_C
test1 some1 1
test2 some2 1
test2 some3 2
test2 some4 3
test3 some5 1
test1 some6 2
test3 some7 2

在 row1 - 'test1' 第一次出现,所以我们在 col_C 中得到 '1';在 row2 - 'test2' 第一次出现,所以我们在 col_C 中得到 '1';在第 3 行 - 'test2' 出现第二次,所以我们在 col_C 中得到 '2' 等等

确实使用了 value_counts,但我只得到 col_C 中 col_A 值的计数。我需要确切的发生。

谢谢您的帮助!

【问题讨论】:

    标签: python pandas dataframe find-occurrences


    【解决方案1】:

    您正在寻找的是来自 groupby 的 cumcount() 。它从 0 开始计算每列中相同值的数量。
    这段代码应该可以工作。

    s = df.groupby('col_A').cumcount()
    df['col_C'] =  s+1
    

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 2021-09-17
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多