Thường cần chuyển đổi kiểu dữ liệu (dtype) của một hoặc nhiều cột trong Pandas DataFrame để phù hợp với tính toán. Pandas cung cấp nhiều phương thức.
1. astype() - Ép kiểu tường minh
import pandas as pd
df = pd.DataFrame({
'DayNo': [1, 2, 3, 4, 5, 6, 7],
'Name': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
'Qty': [2.6, 5, 11.8, 2, 5.6, 0, 0.25]
})
print("Trước:")
print(df.dtypes)
# Chuyển tất cả cột sang string
df_str = df.astype(str)
print("\nSau astype(str):")
print(df_str.dtypes)
Kết quả
Trước: DayNo int64 Name object Qty float64 dtype: object Sau astype(str): DayNo object Name object Qty object dtype: object
Chuyển cột cụ thể:
df['Qty'] = df['Qty'].astype('int32') # Chuyển 1 cột
df[['DayNo', 'Qty']] = df[['DayNo', 'Qty']].astype('float32') # Nhiều cột
2. pd.to_numeric() - Chuyển sang số (an toàn)
Xử lý lỗi chuyển đổi tốt hơn astype().
df_str = df.astype(str) # Tất cả thành string
print(df_str.dtypes)
# Chuyển cột DayNo về numeric
df_num = pd.to_numeric(df_str['DayNo'])
print(f"DayNo dtype: {df_num.dtype}") # int64
# Với errors='coerce': giá trị không chuyển được thành NaN
df['Qty'] = pd.to_numeric(df['Qty'], errors='coerce')
3. infer_objects() - Đ suy luận kiểu mềm
Chuyển cột object sang kiểu cụ thể hơn nếu có thể.
df = pd.DataFrame({
'DayNo': [1, 2, 3, 4, 5, 6, 7],
'Qty': ['2.6', '5', '11.8', '2', '5.6', '0', '0.25']
}, dtype='object')
print("Trước:", df.dtypes)
df_new = df.infer_objects()
print("Sau:", df_new.dtypes)
Kết quả
Trước: DayNo object, Qty object Sau: DayNo int64, Qty object # Qty vẫn object vì chứa string
4. convert_dtypes() - Pandas 1.0+ (Khuyến nghị)
Chuyển sang kiểu nullable dtype tốt hơn (Int64, string, boolean...).
df_converted = df.convert_dtypes() print(df_converted.dtypes)
Tóm tắt khi nào dùng gì
astype(): Biết chắc chắn dtype mục tiêu, cần kiểm soát chính xácto_numeric(): Chuyển string → số, cần xử lý lỗi (coerce/ignore)infer_objects(): Đề xuất kiểu cho cột objectconvert_dtypes(): Tự động chuyển sang nullable dtypes (hiện đại nhất)