简体   繁体   English

熊猫:增量计算列中的出现次数

[英]Pandas: Incrementally count occurrences in a column

I have a DataFrame (df) which contains a 'Name' column. 我有一个DataFrame(df),其中包含一个'Name'列。 In a column labeled 'Occ_Number' I would like to keep a running tally on the number of appearances of each value in 'Name'. 在标有“Occ_Number”的列中,我想保持“名称”中每个值的出现次数的运行记录。

For example: 例如:

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()

but can't quite figure out how to tie it all together. 但无法弄清楚如何将它们联系在一起。 I can only get the grand total from value_counts(). 我只能从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: 到目前为止,我的过程涉及使用以下代码创建包含大于1的计数的“名称”列字符串值的列表:

>things = df['Name'].value_counts()
>things = things[things > 1]
>queries = things.index.values

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. 我希望以某种方式循环“名称”并通过检查查询有条件地添加到Occ_Number,但这是我被卡住的地方。 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: 您可以使用cumcount来避免虚拟列:

>>> 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

You can add a helper column and then use cumsum : 您可以添加辅助列,然后使用cumsum

df =pd.DataFrame({'Name':['abc', 'def', 'ghi', 'abc', 'abc', 'def', 'jkl', 'jkl']})

add count: 添加计数:

df['counts'] =1

group by name: 按名称分组:

cs =df.groupby('Name')['counts'].cumsum()
# set series name
cs.name = 'Occ_number'

join series back to dataframe: 将系列连接回数据帧:

# remove helper column
del df['counts']
df.join(cs)

returns: 收益:

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM