Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโปรแกรม Python แสดงสมาชิกที่ซ้ำมากที่สุดใน Series


อินพุต - สมมติคุณมี Series

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

เอาต์พุต - ผลลัพธ์สมาชิกที่ซ้ำมากที่สุดคือ 3

วิธีแก้ปัญหา

ทำตามขั้นตอนด้านล่าง

  • สร้าง Series

  • ใช้ functools reduce ร่วมกับ lambda เปรียบเทียบจำนวนครั้งที่ซ้ำ

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

ตัวอย่าง

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))

ผลลัพธ์

most repeated element is: 3