Skip to main content
 首页 » 编程设计

python之使用自定义属性保存/加载 Pandas 数据框

2024年09月07日8wuhuacong

我有一个 pandas.DataFrame,我以属性的形式向其附加了一些元信息。我想用这个完整地保存/恢复 df,但它在保存过程中被删除了:

import pandas as pd 
from sklearn import datasets 
iris = datasets.load_iris() 
df = pd.DataFrame(iris.data, columns=iris.feature_names) 
 
df.my_attribute = 'can I recover this attribute after saving?' 
df.to_pickle('test.pkl') 
new_df = pd.read_pickle('test.pkl') 
new_df.my_attribute 
 
# AttributeError: 'DataFrame' object has no attribute 'my_attribute' 

其他文件格式似乎更糟:csv 和 json 丢弃 type、index 或 column 信息,如果你不小心的话。也许创建一个扩展 DataFrame 的新类?对想法持开放态度。

请您参考如下方法:

这里没有通用的或接近标准的东西,但有一些选择

1) 一般建议——除了最短的序列化(比如 <1 天),我不会将 pickle 用于任何事情

2) 可以将任意元数据打包成 pandas 支持的两种二进制格式,msgpack 和 HDF5,以特殊方式授予。您也可以使用 CSV 等来执行此操作,但它会变得更加临时。

# msgpack 
data = {'df': df, 'my_attribute': df.my_attribute} 
pd.to_msgpack('tmp.msg', data) 
pd.read_msgpack('tmp.msg')['my_attribute'] 
# Out[70]: 'can I recover this attribute after saving?' 
 
# hdf 
with pd.HDFStore('tmp.h5') as store: 
    store.put('df', df) 
    store.get_storer('df').attrs.my_attribute = df.my_attribute     
with pd.HDFStore('tmp.h5') as store: 
    df = store.get('df') 
    df.my_attribute = store.get_storer('df').attrs.my_attribute 
 
df.my_attribute 
Out[79]: 'can I recover this attribute after saving?' 

3) xarray , 这是 pandas 支持存储到 NetCDF 文件格式的 n-d 扩展,它具有更内置的元数据概念

import xarray 
ds = xarray.Dataset.from_dataframe(df) 
ds.attrs['my_attribute'] = df.my_attribute 
 
ds.to_netcdf('test.cdf') 
ds = xarray.open_dataset('test.cdf') 
ds 
Out[8]:  
<xarray.Dataset> 
Dimensions:            (index: 150) 
Coordinates: 
  * index              (index) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... 
Data variables: 
    sepal length (cm)  (index) float64 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 ... 
    sepal width (cm)   (index) float64 3.5 3.0 3.2 3.1 3.6 3.9 3.4 3.4 2.9 ... 
    petal length (cm)  (index) float64 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 ... 
    petal width (cm)   (index) float64 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 ... 
Attributes: 
    my_attribute:  can I recover this attribute after saving?