Pandas: 按两列分组并计算第二列中所有值的出现次数

4

我希望使用两列对数据框进行分组,一个是年月(格式为16-10),另一个是客户数。如果客户数大于六个,则要创建一行来替换所有客户数为6+的行,并且总价值数量大于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
1个回答

2

我相信您需要先替换所有值>=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

是的,这个解决方案对我有效。非常感谢您的快速回复。 - punit kumar Sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接