pandas :递增计算一栏中的出现次数 [英] Pandas: Incrementally count occurrences in a column
问题描述
我有一个DataFrame(df),其中包含一个名称"列.在标记为"Occ_Number"的列中,我希望对名称"中每个值的出现次数进行统计.
I have a DataFrame (df) which contains a 'Name' column. In a column labeled 'Occ_Number' I would like to keep a running tally on the number of appearances of each value in 'Name'.
例如:
Name Occ_Number
abc 1
def 1
ghi 1
abc 2
abc 3
def 2
jkl 1
jkl 2
我一直在尝试提出一种使用的方法
I've been trying to come up with a method using
>df['Name'].value_counts()
但无法完全弄清楚如何将它们捆绑在一起.我只能从value_counts()中获得总计.到目前为止,我的过程涉及使用以下代码创建名称"列字符串值的列表,该列表包含大于1的计数:
but can't quite figure out how to tie it all together. I can only get the grand total from value_counts(). My process thus far involves creating a list of the 'Name' column string values which contain counts greater than 1 with the following code:
>things = df['Name'].value_counts()
>things = things[things > 1]
>queries = things.index.values
我当时希望以某种方式在名称"中循环,并通过检查查询有条件地将其添加到Occ_Number中,但这就是我遇到的问题.有人知道这样做的方法吗?我将不胜感激任何帮助.谢谢!
I was hoping to then somehow cycle through 'Name' and conditionally add to Occ_Number by checking against queries, but this is where I'm getting stuck. Does anybody know of a way to do this? I would appreciate any help. Thank you!
推荐答案
You can use cumcount
to avoid a dummy column:
>>> df["Occ_Number"] = df.groupby("Name").cumcount()+1
>>> df
Name Occ_Number
0 abc 1
1 def 1
2 ghi 1
3 abc 2
4 abc 3
5 def 2
6 jkl 1
7 jkl 2
这篇关于 pandas :递增计算一栏中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!