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

วิธีหาค่า Standard Deviation ของ Column เฉพาะใน DataFrame Pandas

Standard Deviation (SD) วัดการกระจายของข้อมูลจากค่าเฉลี่ย ค่า SD สูง = ข้อมูลกระจายกว้าง, ค่า SD ต่ำ = ข้อมูล 모여กลุ่ม

ใน Pandas ใช้ Method .std() บน Series (Column เดียว) หรือ DataFrame (ทุก Column Numeric)

ตัวอย่างโค้ด


import pandas as pd

my_data = {
    'Name': pd.Series(['Tom', 'Jane', 'Vin', 'Eve', 'Will']),
    'Age': pd.Series([45, 67, 89, 12, 23]),
    'value': pd.Series([8.79, 23.24, 31.98, 78.56, 90.20])
}

my_df = pd.DataFrame(my_data)
print("The dataframe is:")
print(my_df)

# SD ของ Column 'Age'
print("\nThe standard deviation of column 'Age' is:")
print(my_df['Age'].std())

# SD ของ Column 'value'
print("\nThe standard deviation of column 'value' is:")
print(my_df['value'].std())

# SD ทุก Numeric Columns พร้อมกัน
print("\nStandard deviation of all numeric columns:")
print(my_df.std())

ผลลัพธ์


The dataframe is:
   Name  Age  value
0  Tom   45   8.79
1  Jane  67  23.24
2  Vin   89  31.98
3  Eve   12  78.56
4  Will  23  90.20

The standard deviation of column 'Age' is:
31.499206339207976

The standard deviation of column 'value' is:
35.747101700697364

Standard deviation of all numeric columns:
Age     31.499206
value   35.747102
dtype: float64

คำอธิบาย

  • สร้าง DataFrame พร้อม Column ตัวเลข (Age, value) และ String (Name)

  • my_df['Age'].std() - เข้าถึง Column 'Age' ได้ Series แล้วเรียก .std()

  • my_df.std() - เรียกบน DataFrame คำนวณ SD ทุก Numeric Columns อัตโนมัติ

พารามิเตอร์สำคัญของ std()


Series.std(axis=0, skipna=True, ddof=1, numeric_only=False)
พารามิเตอร์ค่า Defaultคำอธิบาย
ddof1Delta Degrees of Freedom: 1 = Sample SD, 0 = Population SD
skipnaTrueข้าม NaN ไป
numeric_onlyFalseTrue = คำนวณเฉพาะ Numeric Columns

Population vs Sample Standard Deviation


# Sample SD (ddof=1) - Default, ใช้กับ Sample Data
sample_std = my_df['Age'].std(ddof=1)

# Population SD (ddof=0) - ใช้กับ Population ทั้งหมด
pop_std = my_df['Age'].std(ddof=0)

print(f"Sample SD: {sample_std:.4f}")
print(f"Population SD: {pop_std:.4f}")

Variance (ความแปรปรวน)

ใช้ .var() พารามิเตอร์เหมือนกัน var = std²