ภาพรวม
ใช้ astype() แปลงชนิดข้อมูลของทุกคอลัมน์ใน DataFrame พร้อมกัน โดยส่ง string dtype หรือ dict
ตัวอย่างโค้ด
import pandas as pd
dataFrame = pd.DataFrame({
"Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
"Units": [90, 120, 100, 150, 200, 130]
})
print("DataFrame ...\n", dataFrame)
print("\nDataFrame Types ...\n", dataFrame.dtypes)
# แปลงทั้งหมดเป็น int32
print("\nCast all columns to int32...")
print("\nUpdated DataFrame Types ...\n", dataFrame.astype('int32').dtypes)
ผลลัพธ์
DataFrame ...
Reg_Price Units
0 7000.5057 90
1 1500.0000 120
2 5000.0000 100
3 8000.0000 150
4 9000.7577 200
5 6000.0000 130
DataFrame Types ...
Reg_Price float64
Units int64
dtype: object
Cast all columns to int32...
Updated DataFrame Types ...
Reg_Price int32
Units int32
dtype: object
คำเตือนสำคัญ
- Loss of precision: float64 -> int32 จะตัดทศนิยมทิ้ง (7000.5057 -> 7000)
- Overflow: ค่ามากเกิน int32 max (2,147,483,647) จะ error หรือ wrap around
- แปลง string -> numeric ใช้
pd.to_numeric()ดีกว่า
Best Practice
# แปลงคอลัมน์เฉพาะเจาะจง (ปลอดภัยกว่า)
df = df.astype({'Reg_Price': 'float32', 'Units': 'int32'})
# หรือแปลงคอลัมน์เดียว
df['Units'] = df['Units'].astype('int32')
# ใช้ convert_dtypes() แปลงอัตโนมัติให้เหมาะสม (Pandas 1.0+)
df = df.convert_dtypes()