【问题标题】:Pandas: Groupby two columns and count the occurence of all values for 2nd column熊猫:按两列分组并计算第二列所有值的出现
【发布时间】:2018-01-17 22:58:18
【问题描述】:

我想使用两列对我的数据框进行分组,一列是年月(格式:16-10),另一列是客户数。然后,如果客户的数量超过六,我想创建一行,用 cust = 6+ 的数量和 cust >6 的总值的总和替换所有行。

这就是数据的样子

index     month      num ofcust    count

0            10          1.0         1
1            10          2.0         1
2            10          3.0         1
3            10          4.0         1
4            10          5.0         1
5            10          6.0         1
6            10          7.0         1
7            10          8.0         1
8            11          1.0         1
9            11          2.0         1
10           11          3.0         1
11           12          12.0        1

输出:

index   month   no of cust  count

0       16-10   1.0         3
1       16-10   2.0         6
2       16-10   3.0         2
3       16-10   4.0         3
4       16-10   5.0         4
5       16-10   6+          4
6       16-11   1.0         4
7       16-11   2.0         3
8       16-11   3.0         2
9       16-11   4.0         1
10      16-11   5.0         3
11      16-11   6+          5

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    我相信您需要先替换所有值 >=6,然后再替换 groupby + 聚合 sum

    s = df['num ofcust'].mask(df['num ofcust'] >=6, '6+')
    #alternatively
    #s = df['num ofcust'].where(df['num ofcust'] <6, '6+')
    df = df.groupby(['month', s])['count'].sum().reset_index()
    print (df)
       month num ofcust  count
    0     10          1      1
    1     10          2      1
    2     10          3      1
    3     10          4      1
    4     10          5      1
    5     10         6+      3
    6     11          1      1
    7     11          2      1
    8     11          3      1
    9     12         6+      1
    

    详情

    print (s)
    0      1
    1      2
    2      3
    3      4
    4      5
    5     6+
    6     6+
    7     6+
    8      1
    9      2
    10     3
    11    6+
    Name: num ofcust, dtype: object
    

    另一个非常相似的解决方案是先将数据附加到列:

    df.loc[df['num ofcust'] >= 6, 'num ofcust'] = '6+'
    df = df.groupby(['month', 'num ofcust'], as_index=False)['count'].sum()
    print (df)
       month num ofcust  count
    0     10          1      1
    1     10          2      1
    2     10          3      1
    3     10          4      1
    4     10          5      1
    5     10         6+      3
    6     11          1      1
    7     11          2      1
    8     11          3      1
    9     12         6+      1
    

    【讨论】:

    • 是的,这个解决方案对我有用。非常感谢您的快速回复。
    猜你喜欢
    • 2022-07-06
    • 2021-10-30
    • 1970-01-01
    • 2021-01-16
    • 2020-03-21
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多