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

Python Pandas - ส่งคืนความถี่สัมพัทธ์จากวัตถุดัชนี


ในการคืนค่าความถี่สัมพัทธ์จากวัตถุดัชนี ให้ใช้ index.value_counts() เมธอดที่มีพารามิเตอร์ ทำให้เป็นมาตรฐาน ตามที่ จริง .

ขั้นแรก นำเข้าไลบรารีที่จำเป็น -

import pandas as pd

การสร้างดัชนีนุ่น -

index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])

แสดงดัชนีหมีแพนด้า −

print("Pandas Index...\n",index)

รับจำนวนค่าที่ไม่ซ้ำโดยใช้ value_counts() ตั้งค่าพารามิเตอร์ "normalize" เป็น True เพื่อรับความถี่สัมพัทธ์ -

print("\nGet the relative frequency by dividing all values by the sum of values...\n", index.value_counts(normalize=True))

ตัวอย่าง

ต่อไปนี้เป็นรหัส -

import pandas as pd

# Creating Pandas index
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# Get the count of unique values using value_counts()
# Set the parameter "normalize" to True to get the relative frequency
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