Pandas 使用条件增加 groupby 上的值 [英] Pandas increment values on groupby with a condition
本文介绍了Pandas 使用条件增加 groupby 上的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的 df,需要对链接进行分组,如果一个链接重复超过 3 次,应该增加它的值
Lets say I have a df like this, need to groupby on links, and if a link repeated more than 3 times, should increment its value
name links
A https://a.com/-pg0
B https://b.com/-pg0
C https://c.com/-pg0
D https://c.com/-pg0
x https://c.com/-pg0
y https://c.com/-pg0
z https://c.com/-pg0
E https://e.com/-pg0
F https://e.com/-pg0
预期输出,这里命名为C、D、x、y、z,重复次数超过3次,所以前3个为零,下一个递增
Expected output, here names C,D,x,y,z, repeated more than 3, so first 3 will be zero and next will be incremented
name links
A https://a.com/-pg0
B https://b.com/-pg0
C https://c.com/-pg0
D https://c.com/-pg0
x https://c.com/-pg0
y https://c.com/-pg1
z https://c.com/-pg1
E https://e.com/-pg0
F https://e.com/-pg0
推荐答案
你可以用 //
s = df.groupby('links').cumcount()//3
Out[125]:
0 0
1 0
2 0
3 0
4 0
5 1
6 1
7 0
8 0
dtype: int64
df['links'] = df['links'] + s.astype(str)
这篇关于Pandas 使用条件增加 groupby 上的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文