Вы можете просто использовать 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