![](/img/trans.png)
[英]What is the most efficient way of counting occurrences of a bunch of specific keywords in pandas?
[英]What is the most efficient way of counting occurrences in pandas?
我有一个大的(大约 12M 行)DataFrame df
:
df.columns = ['word','documents','frequency']
以下内容及时运行:
word_grouping = df[['word','frequency']].groupby('word')
MaxFrequency_perWord = word_grouping[['frequency']].max().reset_index()
MaxFrequency_perWord.columns = ['word','MaxFrequency']
但是,这需要很长时间才能运行:
Occurrences_of_Words = word_grouping[['word']].count().reset_index()
我在这里做错了什么? 有没有更好的方法来计算大型 DataFrame 中的出现次数?
df.word.describe()
运行得很好,所以我真的没想到这个Occurrences_of_Words
DataFrame 需要很长时间才能构建。
我认为df['word'].value_counts()
应该服务。 通过跳过 groupby 机制,您将节省一些时间。 我不确定为什么count
应该比max
慢得多。 两者都需要一些时间来避免缺失值。 (与size
比较。)
在任何情况下, value_counts 都经过专门优化以处理对象类型,比如你的话,所以我怀疑你会做得更好。
当您想计算 pandas dataFrame 列中分类数据的频率时,请使用: df['Column_Name'].value_counts()
- 来源。
只是对先前答案的补充。 我们不要忘记,在处理真实数据时可能会有空值,因此使用选项dropna=False
( 默认为True
)将这些值也包括在计数中是很有用的
一个例子:
>>> df['Embarked'].value_counts(dropna=False)
S 644
C 168
Q 77
NaN 2
计算出现次数的其他可能方法可能是使用(i)来自collections
模块的Counter
,(ii)来自numpy
库unique
性和(iii)在pandas
中的groupby
+ size
。
使用collections.Counter
:
from collections import Counter
out = pd.Series(Counter(df['word']))
要使用numpy.unique
:
import numpy as np
i, c = np.unique(df['word'], return_counts = True)
out = pd.Series(c, index = i)
要使用groupby
+ size
:
out = pd.Series(df.index, index=df['word']).groupby(level=0).size()
上述方法中缺少的value_counts
的一个非常好的特性是它对计数进行排序。 如果对计数进行排序是绝对必要的,那么value_counts
是最好的方法,因为它简单且性能好(尽管它仍然比其他方法略胜一筹,尤其是对于非常大的系列)。
如果我们查看运行时,它取决于存储在 DataFrame 列/系列中的数据。
如果 Series 是 dtype 对象,那么对于非常大的 Series,最快的方法是collections.Counter
,但总的来说value_counts
非常有竞争力。
但是,如果是 dtype int,那么最快的方法是numpy.unique
:
用于生成绘图的代码:
import perfplot
import numpy as np
import pandas as pd
from collections import Counter
def creator(n, dt='obj'):
s = pd.Series(np.random.randint(2*n, size=n))
return s.astype(str) if dt=='obj' else s
def plot_perfplot(datatype):
perfplot.show(
setup = lambda n: creator(n, datatype),
kernels = [lambda s: s.value_counts(),
lambda s: pd.Series(Counter(s)),
lambda s: pd.Series((ic := np.unique(s, return_counts=True))[1], index = ic[0]),
lambda s: pd.Series(s.index, index=s).groupby(level=0).size()
],
labels = ['value_counts', 'Counter', 'np_unique', 'groupby_size'],
n_range = [2 ** k for k in range(5, 25)],
equality_check = lambda *x: (d:= pd.concat(x, axis=1)).eq(d[0], axis=0).all().all(),
xlabel = '~len(s)',
title = f'dtype {datatype}'
)
plot_perfplot('obj')
plot_perfplot('int')
我来到这里只是想查找df.column中是否存在“值”,这对我有用:
"value" in df["Column"].values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.