【问题标题】:Count consecutive occurrence's for column [duplicate]计算列的连续出现次数[重复]
【发布时间】:2021-06-02 03:53:42
【问题描述】:

我正在尝试计算 Products 列的连续出现次数。结果应如“总计数”栏中所示。我尝试将 groupby 与 cumsum 一起使用,但我的逻辑无法正常工作

+----------+--------------+
| Products | Total counts |
+----------+--------------+
| 1        | 3            |
+----------+--------------+
| 1        | 3            |
+----------+--------------+
| 1        | 3            |
+----------+--------------+
| 2        | 1            |
+----------+--------------+
| 3        | 3            |
+----------+--------------+
| 3        | 3            |
+----------+--------------+
| 3        | 3            |
+----------+--------------+
| 4        | 2            |
+----------+--------------+
| 4        | 2            |
+----------+--------------+

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    使用groupby 和transform 并计数,

    df['Total counts'] = df.groupby('Products').transform('count')
    

    输出:

       Products  Total counts
    0         1             3
    1         1             3
    2         1             3
    3         2             1
    4         3             3
    5         3             3
    6         3             3
    7         4             2
    8         4             2
    

    Consective Products,稍后在数据框中重复:

    grp = (df['Products'] != df['Products'].shift()).cumsum()
    df['Total counts'] = df.groupby(grp)['Products'].transform('count')
    

    输出:

       Products  Total counts
    0         1             3
    1         1             3
    2         1             3
    3         2             1
    4         3             3
    5         3             3
    6         3             3
    7         4             2
    8         4             2
    

    【讨论】:

    • 也许包括一个选项,其中“连续”方面正在发挥作用?
    • @HenryEcker 点了....谢谢。
    • 我知道你只是错过了它。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多