pandas :递增计算一栏中的出现次数

编程入门 行业动态 更新时间:2024-10-27 11:21:40
本文介绍了 pandas :递增计算一栏中的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个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!

推荐答案

您可以使用 cumcount 避免使用虚拟列:

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 :递增计算一栏中的出现次数

本文发布于:2023-10-14 19:05:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1491938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:栏中   次数   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!