Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chuyển đổi kiểu dữ liệu cột DataFrame (float sang int) Python pandas

Giả sử bạn có cột 'Result' kiểu float64 và muốn chuyển sang int64.

Giải pháp

  • Tạo DataFrame.
  • Chuyển đổi: df['Result'] = df['Result'].astype(int).

Mã ví dụ

import pandas as pd

data = {
    'Name': ['David', 'Adam', 'Bob', 'Alex', 'Serina'],
    'Age': [13, 12, 12, 13, 12],
    'Maths': [98, 59, 66, 95, 70],
    'Science': [75, 96, 55, 49, 78],
    'English': [79, 45, 70, 60, 80],
    'Result': [8.1, 6.2, 6.3, 7.2, 8.3]
}
df = pd.DataFrame(data)

print("Trước chuyển đổi:\n", df.dtypes)

df['Result'] = df['Result'].astype(int)

print("\nSau chuyển đổi:\n", df.dtypes)
print("\nDữ liệu Result:", df['Result'].tolist())

Kết quả

Trước chuyển đổi:
Name       object
Age         int64
Maths       int64
Science     int64
English     int64
Result    float64
dtype: object

Sau chuyển đổi:
Name       object
Age         int64
Maths       int64
Science     int64
English     int64
Result      int64
dtype: object

Dữ liệu Result: [8, 6, 6, 7, 8]

Lưu ý:

  • astype(int) cắt bỏ phần thập phân (truncate), không làm tròn.
  • Nếu cột có NaN, sẽ lỗi (int không hỗ trợ NaN). Dùng pd.Int64Dtype() (nullable integer) hoặc fillna trước.
  • Chuyển nhiều cột: df[['A','B']] = df[['A','B']].astype(int).