如何在 pandas
系列中获取最常见的项?
考虑系列 s
s = pd.Series("1 5 3 3 3 5 2 1 8 10 2 3 3 3".split()).astype(int)
返回的值应为3
如何在 pandas
系列中获取最常见的项?
考虑系列 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
方法,并提取第一个值:res = s.mode().iloc[0]
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
value_counts
并通过index
选择第一个值:val = s.value_counts().index[0]
from collections import Counter
val = Counter(s).most_common(1)[0][0]
_, idx, counts = np.unique(s, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
val = s[index]
pandas.factorize
和 numpy.bincount
这与 @jezrael 的 Numpy 解答非常相似,不同之处在于使用 factorize
而不是 numpy.unique
factorize
返回一个整数分解和唯一值bincount
计算每个唯一值出现的次数argmax
确定最频繁的 bin 或 factorargmax
返回的 bin 位置引用唯一值数组中的最频繁值i, r = s.factorize()
r[np.bincount(i).argmax()]
3
pd.Series.mode
。 - jppfrom scipy import stats
import pandas as pd
x=[1,5,3,3,3,5,2,1,8,10,2,3,3,3]
data=pd.DataFrame({"values":x})
print(stats.mode(data["values"]))
output:-ModeResult(mode=array([3], dtype=int64), count=array([6]))