ในการหาความถี่สัมพัทธ์ (relative frequency) ของค่าในดัชนี (Index) ให้ใช้เมธอด index.value_counts() พร้อมตั้งค่าพารามิเตอร์ normalize=True
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้างดัชนี
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
3. แสดงดัชนี
print("Pandas Index...\n", index)
4. หาความถี่สัมพัทธ์
print("\nGet the relative frequency by dividing all values by the sum of values...\n", index.value_counts(normalize=True))
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# สร้างดัชนี
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
# แสดงดัชนี
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)
# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)
# หาความถี่สัมพัทธ์
print("\nGet the relative frequency by dividing all values by the sum of values...\n", index.value_counts(normalize=True))
ผลลัพธ์
Pandas Index... Int64Index([50, 10, 70, 110, 90, 50, 110, 90, 30], dtype='int64')
Number of elements in the index... 9
The dtype object... int64
Get the relative frequency by dividing all values by the sum of values...
50 0.222222
110 0.222222
90 0.222222
10 0.111111
70 0.111111
30 0.111111
dtype: float64
คำอธิบาย
normalize=True ทำให้ผลลัพธ์เป็นสัดส่วน (ความถี่หารด้วยจำนวนทั้งหมด 9) ค่า 50, 110, 90 ปรากฏ 2 ครั้ง = 2/9 ≈ 0.222 อื่นๆ 1 ครั้ง = 1/9 ≈ 0.111