Write a Pandas program to display most frequent value in a given series and replace everything else as ‘Other’ in the series.
import pandas as pd import numpy as np np.random.RandomState(100) num_series = pd.Series(np.random.randint(1, 5, [15])) print("Original Series:") print(num_series) print("Top 2 Freq:", num_series.value_counts()) result = num_series[~num_series.isin(num_series.value_counts().index[:1])] = 'Other' print(num_series)
Sample Output:
Original Series: 0 3 1 1 2 1 3 3 4 2 5 2 6 1 7 2 8 3 9 1 10 2 11 2 12 2 13 3 14 3 dtype: int64 Top 2 Freq: 2 6 3 5 1 4 dtype: int64 0 Other 1 Other 2 Other 3 Other 4 2 5 2 6 Other 7 2 8 Other 9 Other 10 2 11 2 12 2 13 Other 14 Other dtype: object
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output: