【问题标题】:pandas - How to save only selected columns of a DataFrame to HDF5pandas - 如何仅将 DataFrame 的选定列保存到 HDF5
【发布时间】:2015-03-08 20:23:06
【问题描述】:

我正在读取一个 csv 示例文件并将其存储在 .h5 数据库中。 .csv 的结构如下:

User_ID;Longitude;Latitude;Year;Month;String
267261661;-3.86580025;40.32170825;2013;12;hello world
171255468;-3.83879575;40.05035005;2013;12;hello world
343588169;-3.70759531;40.4055946;2014;2;hello world
908779052;-3.8356385;40.1249459;2013;8;hello world
289540518;-3.6723114;40.3801642;2013;11;hello world
635876313;-3.8323166;40.3379393;2012;10;hello world
175160914;-3.53687933;40.35101274;2013;12;hello world 
155029860;-3.68555076;40.47688417;2013;11;hello world

我已经将它放在带有 pandas to_hdf 的 .h5 存储中,选择仅将几列传递给 .h5:

import pandas as pd

df = pd.read_csv(filename + '.csv', sep=';')

df.to_hdf('test.h5','key1',format='table',data_columns=['User_ID','Year'])

我使用 HDFStore 和 read_hdf 在 .h5 文件中存储的列中获得了不同的结果,特别是:

store = pd.HDFStore('test.h5')
>>> store
>>> <class 'pandas.io.pytables.HDFStore'>
File path: /test.h5
/key1            frame_table  (typ->appendable,nrows->8,ncols->6,indexers->[index],dc->[User_ID,Year])

这是我所期望的(数据库中仅存储了“User_ID”和“Year”列),尽管 ncols->6 意味着实际上所有列都已存储在 .h5 文件中。

如果我尝试使用 pd.read_hdf 读取文件:

hdf = pd.read_hdf('test.h5','key1')

并要求钥匙:

hdf.keys()
>>> Index([u'User_ID', u'Longitude', u'Latitude', u'Year', u'Month', u'String'], dtype='object')

这不是我所期望的,因为原始 .csv 文件的所有列仍在 .h5 数据库中。如何在 .h5 中仅存储选择的列以减小数据库的大小?

感谢您的帮助。

【问题讨论】:

    标签: python pandas hdf5 hdfstore


    【解决方案1】:

    只需在写入文件时选择列。

    cols_to_keep = ['User_ID', 'Year']
    df.loc[:, cols_to_keep].to_hdf(...)
    

    【讨论】:

    • 太棒了!确实如此简单……所以 read_hdf 中的“data_columns”只是为了说明某些列在以后读取 .h5 文件时是可选的?
    • 我对 hdf5 文件一无所知。你就靠自己了。 (@fblamanna)
    • @fblamanna 这正是 data_columns 的用途,如文档中所示:pandas.pydata.org/pandas-docs/stable/…
    猜你喜欢
    • 2020-03-01
    • 2019-01-16
    • 1970-01-01
    • 2016-05-12
    • 2016-11-22
    • 1970-01-01
    • 2016-06-08
    相关资源
    最近更新 更多