Write a Python program to keep only top 2 most frequent values as it is and replace everything else as ‘Other’ in a series


Topic: Write a Python program to keep only top 2 most frequent values as it is and replace everything else as ‘Other’ in a series

Solution

import pandas as pd
import numpy as np
np.random.RandomState(100)
ser = pd.Series(np.random.randint(1, 5, [12]))
ser[~ser.isin(ser.value_counts().index[:2])] = 'Other'
print(ser)



List all Python Programs