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

Xuất DataFrame ra file Pickle và đọc lại trong Python pandas

Giả sử bạn muốn lưu DataFrame vào định dạng Pickle (nhị phân, nhanh, giữ kiểu dữ liệu) và đọc ngược lại.

Giải pháp

  • Tạo DataFrame.
  • Ghi file: df.to_pickle('pandas.pickle').
  • Đọc file: pd.read_pickle('pandas.pickle').

Mã ví dụ

import pandas as pd

df = pd.DataFrame({
    'Fruits': ["Apple", "Orange", "Mango", "Kiwi"],
    'City': ["Shimla", "Sydney", "Lucknow", "Wellington"]
})

print("Xuất ra file pickle...")
df.to_pickle('pandas.pickle')

print("Đọc từ file pickle:")
result = pd.read_pickle('pandas.pickle')
print(result)

Kết quả

Xuất ra file pickle...
Đọc từ file pickle:
   Fruits       City
0   Apple     Shimla
1  Orange     Sydney
2   Mango    Lucknow
3    Kiwi  Wellington

Lưu ý:

  • Pickle là định dạng Python native, không an toàn nếu load file từ nguồn không tin cậy (có thể chạy mã độc).
  • Lưu trữ: Index, dtypes, MultiIndex, v.v.
  • Nhanh hơn CSV/JSON cho DataFrame lớn.
  • Để chia sẻ an toàn: dùng Parquet, Feather, CSV.