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
397 views
in Technique[技术] by (71.8m points)

python - Grouping and auto increment based on columns in pandas

i have a pandas frame that looks like this:

enter image description here

Is there a way to add the numbers in the last column without having to iterate through the data frame?

I was playing with the results of Grouping and auto incrementing group id in pandas but haven't made it work for my purposes

Here is the code to produce the dataframe

import pandas as pd
columns = ['Product','SubProd', 'NeedThis']
Index=['4/20/2012','4/27/2012','5/4/2012','5/11/2012','5/18/2012','4/20/2012',
'4/27/2012','5/4/2012','5/11/2012','5/18/2012','5/25/2012','10/31/2014','11/7/2014',
'11/14/2014','11/21/2014','11/28/2014']
datas = {'Product' : ['A','A','A','A','A','A','A','A','A','A','A','B','B','B','B','B'],
      'SubProd' : ['BL','BL','BL','BL','BL','lk','lk','lk','lk','lk','lk','po','po','po','po','po']}
df = pd.DataFrame(data=datas, index=Index)
print(df)

Output:

           Product SubProd
4/20/2012        A      BL
4/27/2012        A      BL
5/4/2012         A      BL
5/11/2012        A      BL
5/18/2012        A      BL
4/20/2012        A      lk
4/27/2012        A      lk
5/4/2012         A      lk
5/11/2012        A      lk
5/18/2012        A      lk
5/25/2012        A      lk
10/31/2014       B      po
11/7/2014        B      po
11/14/2014       B      po
11/21/2014       B      po
11/28/2014       B      po

Thanks

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
In [10]: df['counter'] = df.groupby(['Product','SubProd']).cumcount()+1

In [11]: df
Out[11]: 
           Product SubProd  counter
4/20/2012        A      BL        1
4/27/2012        A      BL        2
5/4/2012         A      BL        3
5/11/2012        A      BL        4
5/18/2012        A      BL        5
4/20/2012        A      lk        1
4/27/2012        A      lk        2
5/4/2012         A      lk        3
5/11/2012        A      lk        4
5/18/2012        A      lk        5
5/25/2012        A      lk        6
10/31/2014       B      po        1
11/7/2014        B      po        2
11/14/2014       B      po        3
11/21/2014       B      po        4
11/28/2014       B      po        5

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

Just Browsing Browsing

[4] html - How to create even cell spacing within a

2.1m questions

2.1m answers

60 comments

57.0k users

...