Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

python - Count each group sequentially pandas

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

Anticipated result:

    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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're looking for 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 simply gives each group a label.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...