python - pandas 系列中的独特值计数

标签 python pandas series

我有一个 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 of 使用 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/

相关文章:

python Pandas 错误: too many indices for array

python - 将日期(系列)列从一个 DataFrame 添加到另一个 Pandas,Python

python - 递增数组/系列中的连续正组

python - 如何摆脱matplotlib中条形标签上的科学记数法?

Python:创建前 n 个斐波那契数列

python - SQL语法错误:1064,如何修复?

python - ngram 计数后如何在数据框中添加额外的列

SQL Pandas DataFrame中的where in子句使用列

python - 从文本文件导入列表以使用 isin() 与数据帧进行比较

python - 我该如何解决 : dictionary and list work