按顺序计算每组 pandas [英] Count each group sequentially pandas
本文介绍了按顺序计算每组 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个按两列分组的 df.我想按顺序计算每个组.下面的代码按顺序计算组中的每一行.这似乎比我想象的要容易,但无法弄清楚.
I have a df that I am grouping by two columns. I want to count each group sequentially. The code below counts each row within a group sequentially. This seems easier than I think but can't figure it out.
df = pd.DataFrame({
'Key': ['10003', '10009', '10009', '10009',
'10009', '10034', '10034', '10034'],
'Date1': [20120506, 20120506, 20120506, 20120506,
20120620, 20120206, 20120206, 20120405],
'Date2': [20120528, 20120507, 20120615, 20120629,
20120621, 20120305, 20120506, 20120506]
})
df['Count'] = df.groupby(['Key','Date1']).cumcount() + 1
预期结果:
Date1 Date2 Key Count
0 20120506 20120528 10003 1
1 20120506 20120507 10009 2
2 20120506 20120615 10009 2
3 20120506 20120629 10009 2
4 20120620 20120621 10009 3
5 20120206 20120305 10034 4
6 20120206 20120506 10034 4
7 20120405 20120506 10034 5
推荐答案
您正在寻找 groupby
+ ngroup
:
df['Count'] = df.groupby(['Key','Date1']).ngroup() + 1
df
Date1 Date2 Key Count
0 20120506 20120528 10003 1
1 20120506 20120507 10009 2
2 20120506 20120615 10009 2
3 20120506 20120629 10009 2
4 20120620 20120621 10009 3
5 20120206 20120305 10034 4
6 20120206 20120506 10034 4
7 20120405 20120506 10034 5
ngroup
只是给每个组一个标签.
ngroup
simply gives each group a label.
这篇关于按顺序计算每组 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文