用Python编写程序以查找系列中重复次数最多的元素

假设您有以下系列,

Series is:
0    1
1    22
2    3
3    4
4    22
5    5
6    22

而最重复的元素的结果是,

重复的元素是: 22

解决方案

为了解决这个问题,我们将遵循以下方法,

  • 定义系列

  • 设置初始计数为0,并将max_count值设置为系列的第一个元素值数据[0]

count = 0
max_count = data[0]

  • 创建for循环以访问序列数据,并将frequency_count设置为 l.count(i)

for i in data:
   frequency_count = l.count(i)

  • 设置条件是否要与max_count值进行比较,如果条件为true,则将count分配给frequency_count并将max_count更改为series present元素。最后,打印max_count。它的定义如下

if(frequency_count > max_count):
   count = frequency_count
   max_count = i

print("重复的元素是:", max_count)

例子

让我们看一下下面的实现以获得更好的理解-

import pandas as pd
l = [1,22,3,4,22,5,22]
data = pd.Series(l)
print("Series is:\n", data)
count = 0
max_count = data[0]
for i in data:
   frequency_count = l.count(i)
   if(frequency_count > max_count):
      count = frequency_count
      max_count = i
print("重复的元素是:", max_count)

输出

Series is:
0    1
1    22
2    3
3    4
4    22
5    5
6    22
dtype: int64
重复的元素是: 22

猜你喜欢