pandas: How to get the most frequent item in pandas series?

  • A+
Category:Languages

How can I get the most frequent item in a pandas series?

Consider the series s

s = pd.Series("1 5 3 3 3 5 2 1 8 10 2 3 3 3".split()).astype(int) 

The returned value should be 3

 


Use value_counts and select first value by index:

val = s.value_counts().index[0] 

Or Counter.most_common:

from collections import Counter  val = Counter(s).most_common(1)[0][0] 

Or numpy solution:

_, idx, counts = np.unique(s, return_index=True, return_counts=True) index = idx[np.argmax(counts)] val = s[index] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: