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

Python – แปลง Data Type ของคอลัมน์เดียวใน Pandas DataFrame ด้วย astype()

ภาพรวม

ใช้ astype() แปลงชนิดข้อมูลของคอลัมน์เฉพาะคอลัมน์ โดยส่ง dictionary {'column_name': 'new_type'}

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

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)

# แปลงคอลัมน์ Units จาก int64 เป็น int32
print("\nCast only a single column to int32...")
print("\nUpdated DataFrame Types ...\n", dataFrame.astype({'Units': '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 only a single column to int32...
Updated DataFrame Types ...
Reg_Price    float64
Units          int32
dtype: object

การใช้งาน astype() เพิ่มเติม

# แปลงหลายคอลัมน์พร้อมกัน
df.astype({'col1': 'int32', 'col2': 'float32', 'col3': 'string'})

# แปลงทั้ง DataFrame (ทุกคอลัมน์)
df.astype('int32')  # ลองแปลงทั้งหมด error ถ้ามีคอลัมน์ string

# แปลงคอลัมน์เดียวแบบ inplace (Pandas 1.3+)
df['Units'] = df['Units'].astype('int32')

# ตรวจสอบก่อนแปลง
df['Units'].dtype  # int64

ชนิดข้อมูลที่ใช้บ่อย

  • int8, int16, int32, int64
  • float16, float32, float64
  • bool, object, string, category
  • datetime64[ns], timedelta64[ns]