gpt4 book ai didi

python - 基于 Pandas 列的分组和自动递增

转载 作者:太空宇宙 更新时间:2023-11-04 01:00:42 25 4
gpt4 key购买 nike

我有一个看起来像这样的 pandas 框架:

enter image description here

有没有一种方法可以在不必遍历数据框的情况下将数字添加到最后一列?

我正在玩 Grouping and auto incrementing group id in pandas 的结果但还没有让它为我的目的工作

这是生成数据框的代码

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)

输出:

           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

谢谢

最佳答案

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

关于python - 基于 Pandas 列的分组和自动递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32998699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com