Pandas:Groupby两列并计算第二列

时间:2018-01-17 14:46:56

标签: python pandas pandas-groupby

我想使用两列来分组我的数据框,一列是一年(格式:16-10),另一列是cust的数量。然后,如果暗偶的数量多于六个,我想创建一行,用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

1 个答案:

答案 0 :(得分: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