gpt4 book ai didi

python Pandas : Counting element occurrences in series

转载 作者:行者123 更新时间:2023-12-01 22:19:23 24 4
gpt4 key购买 nike

如何找到系列元素计数?使用此代码:

import pandas as pd

d = { 'x' : [1,2,2,2,3,4,5,5,7] }
df = pd.DataFrame(d)
cnt1 = len(df[df.x == 1])
cnt2 = len(df[df.x == 2])
cnt3 = len(df[df.x == 3])
...

帮助不大。有什么方法可以计算元素的出现次数,所以结果将是一个包含“元素,计数”对的字典,如下所示:

cnts = {'1':1, '2': 3, '3':1, ...}

或者其他一些易于查找和迭代的结构?

最佳答案

您可以使用 value_counts。它返回一个可以像字典一样查找的系列,您可以对其进行迭代:

df['x'].value_counts(sort=False)
Out:
1 1
2 3
3 1
4 1
5 2
7 1
Name: x, dtype: int64

如果需要,您也可以将其转换为字典:

df['x'].value_counts().to_dict()
Out: {1: 1, 2: 3, 3: 1, 4: 1, 5: 2, 7: 1}

关于 python Pandas : Counting element occurrences in series,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41313982/

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