Write a program in Python to print the most frequently repeated element in a series

PythonPandasServer Side ProgrammingProgramming

Input − Assume, you have a Series,

0    1
1    2
2    3
3    2
4    3
5    3
6    3
7    4
8    4
9    2

Output − And, the result for a most repeated element is 3.

Solution

To solve this, we will follow the steps given below −

  • Define a Series

  • Apply functools reduce method inside lambda function to compare the length of all the elements one by another. It is defined below,

ft.reduce(lambda x,y:x if(len(data[data==x])>len(data[data==y])) else y,data)

Example

Let us see the following implementation to get a better understanding.

import pandas as pd
import functools as ft
l = [1,2,3,2,3,3,3,4,4,2]
data = pd.Series(l)
print("most repeated element is:", ft.reduce(lambda x,y:x
if(len(data[data==x])>len(data[data==y])) else y,data))

Output

most repeated element is: 3
raja
Published on 10-Feb-2021 13:12:05
Advertisements