สมมติว่าคุณมี DataFrame และต้องการจำกัดค่าให้อยู่ในช่วงที่กำหนด (clipping) โดยใช้ค่าขั้นต่ำและสูงสุด
วิธีแก้ปัญหา
- สร้าง DataFrame
- ใช้
df.clip(lower=30)ตัดค่าต่ำกว่า 30 ให้เป็น 30 - ใช้
df.clip(upper=50)ตัดค่าสูงกว่า 50 ให้เป็น 50 - ใช้
df.clip(lower=30, upper=50)ตัดทั้งสองข้างพร้อมกัน
ตัวอย่างโค้ด
import pandas as pd
data = {"Column1": [12, 34, 56, 78, 28], "Column2": [23, 30, 25, 50, 90]}
df = pd.DataFrame(data)
print("DataFrame ต้นฉบับ:\n", df)
print("\nค่าขั้นต่ำ (lower=30):")
print(df.clip(lower=30))
print("\nค่าสูงสุด (upper=50):")
print(df.clip(upper=50))
print("\nตัดทั้งสองข้าง (lower=30, upper=50):")
print(df.clip(lower=30, upper=50))
ผลลัพธ์
DataFrame ต้นฉบับ:
Column1 Column2
0 12 23
1 34 30
2 56 25
3 78 50
4 28 90
ค่าขั้นต่ำ (lower=30):
Column1 Column2
0 30 30
1 34 30
2 56 30
3 78 50
4 30 90
ค่าสูงสุด (upper=50):
Column1 Column2
0 12 23
1 34 30
2 50 25
3 50 50
4 28 50
ตัดทั้งสองข้าง (lower=30, upper=50):
Column1 Column2
0 30 30
1 34 30
2 50 30
3 50 50
4 30 50
คำอธิบาย: clip() ใช้จำกัดค่าใน DataFrame ให้อยู่ในช่วงที่กำหนด ค่าที่น้อยกว่า lower จะถูกตั้งเป็น lower ค่าที่มากกว่า upper จะถูกตั้งเป็น upper ใช้ได้ทั้ง per-column (ส่ง Series) หรือ scalar สำหรับทั้ง DataFrame