使用自定义属性保存/加载 pandas 数据框

ano*_*n01 5 python object pickle pandas

我已经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'
Run Code Online (Sandbox Code Playgroud)

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

chr*_*isb 4

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

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?'
Run Code Online (Sandbox Code Playgroud)

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

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?
Run Code Online (Sandbox Code Playgroud)

  • 我懂了。我收到一条警告,指出 hdf5 无法序列化 df 中的“dict”条目,并诉诸酸洗 - 我想这些担忧在这种情况下仍然适用...... (2认同)