根据 pandas 中的列进行分组和自动递增 [英] Grouping and auto increment based on columns in pandas
本文介绍了根据 pandas 中的列进行分组和自动递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的熊猫框:
i have a pandas frame that looks like this:
有没有一种方法可以在最后一列中添加数字而不必遍历数据框?
Is there a way to add the numbers in the last column without having to iterate through the data frame?
我正在玩结果并分组并自动递增组ID在熊猫中,但出于我的目的而没有使它起作用
I was playing with the results of Grouping and auto incrementing group id in pandas but haven't made it work for my purposes
这是生成数据框的代码
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)
谢谢
推荐答案
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
这篇关于根据 pandas 中的列进行分组和自动递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文