Python Pandas: Display most frequent value in a given series and replace everything else as ‘Other’ in the series
Python Pandas: Data Series Exercise-20 with Solution
Write a Pandas program to display most frequent value in a given series and replace everything else as ‘Other’ in the series.
Sample Solution :
Python Code :
import pandas as pd import numpy as np np.random.RandomState(100) num_series = pd.Series(np.random.randint(1, 5, )) 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'
Original Series: 0 4 1 3 2 4 3 3 4 4 5 1 6 2 7 4 8 4 9 2 10 3 11 3 12 1 13 2 14 1 dtype: int64 Top 2 Freq: 4 5 3 4 2 3 1 3 dtype: int64
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to calculate the frequency counts of each unique value of a given series.
Next: Write a Pandas program to find the positions of numbers that are multiples of 5 of a given series.
What is the difficulty level of this exercise?
Test your Python skills with w3resource's quiz
Python: Tips of the Day
Python: Unpack a Tuple
>>> items = (0, 'b', 'one', 10, 11, 'zero') >>> a, b, c, d, e, f = items >>> print(f) zero >>> a, *b, c = items >>> print(b) ['b', 'one', 10, 11] >>> *_, a, b = items >>> print(a) 11
- New Content published on w3resource :
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework