gpt4 book ai didi

python - pandas 系列中的唯一值计数

转载 作者:太空宇宙 更新时间:2023-11-04 02:23:15 25 4
gpt4 key购买 nike

我有一个 Pandas 系列的长字符串。

我想获取整个系列中单词的值计数。我试过

df.value_counts().to_dict()

但它给出的是字符串级别计数而不是单词级别计数。

我怎样才能有效地做到这一点?

我的系列如下所示

print df.head(3)

0 4632 N. Rockwell Street, Chicago Rockwell Neighborhood 773 60625 4748 N Kedzie

1 4632 N. Rockwell Street, Chicago Rockwell' Bdoy 773 60625 4632 N Rock

2 4632 N. Rockwell Street, LA Rock hood Grill 773 60625 3658 W Lawren

我想生成一个字典如下

a['4632'] = 3
a['Rockwell'] = 3
a['LA'] = 1

等等

最佳答案

我认为这是更好的纯 python 解决方案 Counter使用 split 将所有值连接到长字符串:

from collections import Counter

d = Counter(' '.join(df).split())
#if necessary convert to dict
#d = dict(Counter(' '.join(df).split()))

或者使用splitstack第一:

d = df.str.split(expand=True).stack().value_counts().to_dict()
print (d)
{'Rockwell': 4, '4632': 4, 'Street,': 3, '773': 3, '60625': 3, 'N.': 3, 'N': 2, 'Rock': 2, 'Chicago': 2, 'Kedzie': 1, 'Grill': 1, 'Neighborhood': 1, '3658': 1, 'Lawren': 1, 'W': 1, '4748': 1, 'LA': 1, 'hood': 1, "Rockwell'": 1, 'Bdoy': 1}

关于python - pandas 系列中的唯一值计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51077590/

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