สมมติว่าคุณมี Series และต้องการหาค่าที่เกิดขึ้นบ่อยที่สุด (mode)
วิธีแก้ปัญหา (Manual counting)
- สร้าง Series
- นับความถี่ของแต่ละค่า แล้วหาค่าที่มีความถี่มากที่สุด
ตัวอย่างโค้ด (Manual)
import pandas as pd
l = [1, 22, 3, 4, 22, 5, 22]
data = pd.Series(l)
print("Series:\n", data)
count = 0
max_count = data[0]
for i in data:
frequency_count = l.count(i)
if frequency_count > count:
count = frequency_count
max_count = i
print("\nค่าที่ซ้ำมากที่สุด (manual):", max_count)
ผลลัพธ์
Series:
0 1
1 22
2 3
3 4
4 22
5 5
6 22
dtype: int64
ค่าที่ซ้ำมากที่สุด (manual): 22
วิธีที่ง่ายกว่า: ใช้ value_counts() หรือ mode()
# ใช้ value_counts() หาความถี่
print("\nความถี่แต่ละค่า:")
print(data.value_counts())
# ใช้ mode() หาค่าที่พบบ่อยที่สุดโดยตรง
print("\nMode (ค่าที่พบบ่อยที่สุด):")
print(data.mode())
ผลลัพธ์เพิ่มเติม
ความถี่แต่ละค่า:
22 3
1 1
3 1
4 1
5 1
dtype: int64
Mode (ค่าที่พบบ่อยที่สุด):
0 22
dtype: int64
คำอธิบาย:
value_counts()คืนค่า Series ที่ index คือค่าเดิม และ value คือจำนวนครั้ง เรียงจากมากไปน้อยmode()คืนค่า mode (อาจมีหลายค่าถ้ามีค่าที่พบบ่อยเท่ากัน)- วิธี manual ใช้ loop และ count() ทำงานช้ากว่า (O(n²)) เหมาะสำหรับการเรียนรู้ algorithm