【问题标题】:How to write a large csv file to hdf5 in python?如何在python中将一个大的csv文件写入hdf5?
【发布时间】:2018-03-19 03:07:26
【问题描述】:

我的数据集太大而无法直接读入内存。而且我不想升级机器。根据我的阅读,HDF5 可能是解决我问题的合适方法。但我不确定如何将数据帧迭代写入 HDF5 文件,因为我无法将 csv 文件作为数据帧对象加载。

所以我的问题是如何使用 python pandas 将大型 CSV 文件写入 HDF5 文件。

【问题讨论】:

    标签: python pandas hdf5


    【解决方案1】:

    您可以使用chunksize参数分块读取CSV文件并将每个块附加到HDF文件中:

    hdf_key = 'hdf_key'
    df_cols_to_index = [...] # list of columns (labels) that should be indexed
    store = pd.HDFStore(hdf_filename)
    
    for chunk in pd.read_csv(csv_filename, chunksize=500000):
        # don't index data columns in each iteration - we'll do it later ...
        store.append(hdf_key, chunk, data_columns=df_cols_to_index, index=False)
        # index data columns in HDFStore
    
    store.create_table_index(hdf_key, columns=df_cols_to_index, optlevel=9, kind='full')
    store.close()
    

    【讨论】:

    • 感谢您的回答。我不熟悉 pytables 包。可以使用h5py吗?
    • Pandas 基于 pytables 实现了自己的 HDF API - 出于兼容性原因,我们应该使用该 API...
    • @YanSong,但坦率地说,我不明白使用基于 pytables 的内部 Pandas 方法有什么问题 - 你不需要知道任何关于 pytables 的信息即可使用 Pandas HDF 方法...
    • 如果cols number > 2000,这种方式会失败
    • @G_KOBELIEF 请说明失败的表现。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 2017-05-20
    • 2014-02-04
    • 1970-01-01
    相关资源
    最近更新 更多