Skip to content
English
  • There are no suggestions because the search field is empty.

How Do You Keep Only the Top Two Most Frequent Values as It Is and Replace Everything Else as ‘other’ in a Series?

>> #Input
 
>>import pandas as pd
 
>>np.random.RandomState(100)
 
>>ser = pd.Series(np.random.randint(1, 5, [12]))
 
>> #Solution
 
>>print("Top 2 Freq:", ser.value_counts())
 
>>ser[~ser.isin(ser.value_counts().index[:2])] = 'Other’
 
>>ser