ภาพรวม
ใช้เมธอด std() ของ Series/DataFrame คำนวณค่าคลาดเบี่ยงเบนมาตรฐาน (Sample standard deviation โดย default ddof=1)
ตัวอย่างโค้ด
import pandas as pd
dataFrame1 = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
})
dataFrame2 = pd.DataFrame({
"Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],
"Price": [8000, 500, 3000, 1500, 3000, 4000]
})
print("DataFrame1 ...\n", dataFrame1)
print("Standard Deviation of Units:", dataFrame1['Units'].std())
print("\nDataFrame2 ...\n", dataFrame2)
print("Standard Deviation of Price:", dataFrame2['Price'].std())
ผลลัพธ์
DataFrame1 ...
Car Units
0 BMW 100
1 Lexus 150
2 Audi 110
3 Tesla 80
4 Bentley 110
5 Jaguar 90
Standard Deviation of Units: 24.2212028328
DataFrame2 ...
Product Price
0 TV 8000
1 PenDrive 500
2 HeadPhone 3000
3 EarPhone 1500
4 HDD 3000
5 SSD 4000
Standard Deviation of Price: 2601.28173535
พารามิเตอร์ ddof (Delta Degrees of Freedom)
ddof=1(default) – Sample standard deviation (แบ่งด้วย n-1)ddof=0– Population standard deviation (แบ่งด้วย n)
s = pd.Series([100, 150, 110, 80, 110, 90])
print(s.std(ddof=1)) # 24.22 (sample)
print(s.std(ddof=0)) # 22.11 (population)
คำนวณหลายคอลัมน์พร้อมกัน
# ทุกคอลัมน์ numeric
df.std()
# คอลัมน์เฉพาะ
df[['Units', 'Price']].std()
# แบบ DataFrame.agg
df.agg({'Units': 'std', 'Price': ['std', 'mean']})
NaN Handling
std()ข้าม NaN อัตโนมัติ (skipna=True default)- ถ้าทุกค่าเป็น NaN หรือมี 1 ค่า -> NaN