【问题标题】:Save/load pandas dataframe with custom attributes使用自定义属性保存/加载熊猫数据框
【发布时间】:2018-02-16 17:55:23
【问题描述】:

我有一个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'

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

【问题讨论】:

    标签: python pandas object pickle


    【解决方案1】:

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

    1) 一般建议 - 除了最短的术语序列化(例如

    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?
    

    【讨论】:

    • 好奇:为什么你建议 hdf5 而不是 pickle?另外:你对羽毛有什么经验吗?很好的答案,我现在正在测试它......
    • 稳定性 - HDF5 是一种已发布的标准/格式,具有大量现有数据、适用于其他语言的工具,并且应该相对向前兼容。 Pickle 是特定于 python 的,在 python 版本中不一定是稳定的。
    • 是的,羽毛(也看看镶木地板)是不错的选择,不太确定它们的元数据情况
    • 我明白了。我收到一个警告,说 hdf5 无法序列化 df 中的 dict 条目,并诉诸酸洗 - 我想这些问题在这种情况下仍然适用......
    猜你喜欢
    • 2013-10-12
    • 2021-10-14
    • 1970-01-01
    • 2022-12-10
    • 2023-04-03
    • 2012-11-30
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多