pandas:如何获取pandas系列中出现频率最高的项目? [英] pandas: How to get the most frequent item in pandas series?
本文介绍了pandas:如何获取pandas系列中出现频率最高的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获得 pandas
系列中出现频率最高的项目?
How can I get the most frequent item in a pandas
series?
考虑系列s
s = pd.Series("1 5 3 3 3 5 2 1 8 10 2 3 3 3".split()).astype(int)
返回值应该是3
推荐答案
你可以只使用 pd.Series.mode
并提取第一个值:
You can just use pd.Series.mode
and extract the first value:
res = s.mode().iloc[0]
这不一定效率低下.与往常一样,使用您的数据进行测试,看看哪些适合.
This not necessarily inefficient. As always, test with your data to see what suits.
import numpy as np, pandas as pd
from scipy.stats.mstats import mode
from collections import Counter
np.random.seed(0)
s = pd.Series(np.random.randint(0, 100, 100000))
def jez_np(s):
_, idx, counts = np.unique(s, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
val = s[index]
return val
def pir(s):
i, r = s.factorize()
return r[np.bincount(i).argmax()]
%timeit s.mode().iloc[0] # 1.82 ms
%timeit pir(s) # 2.21 ms
%timeit s.value_counts().index[0] # 2.52 ms
%timeit mode(s).mode[0] # 5.64 ms
%timeit jez_np(s) # 8.26 ms
%timeit Counter(s).most_common(1)[0][0] # 8.27 ms
这篇关于pandas:如何获取pandas系列中出现频率最高的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文