【问题标题】:Convert hundreds of csv files into hdf5 files将数百个 csv 文件转换为 hdf5 文件
【发布时间】:2020-04-18 00:46:05
【问题描述】:

我为这个问题找到了很多答案,但没有找到我具体想做的事情。 我有很多 csv 文件,有几行超过 200mo,总共有 ~70Go 的数据,我想将它们转换成 hdf5 文件。

我找到了创建大数据框并将它们连接在一起的方法,但我的数据太大而无法放入单个数据框,使用此处显示的解决方案。 https://datascience.stackexchange.com/questions/53125/file-converter-from-csv-to-hdf5

我正在尝试对每个文件执行 1 个数据帧之类的操作,并将它们全部转换为 hdf5 文件,以便我拥有相同数量的 h5 文件和 csv,但我不知道这是正确的解决方案,因为我不知道没想到我的电脑能把这一切都保存在内存中。

我在另一个 SO 线程上发现了类似的东西,可以在转换之前将所有 csv 放在一个数据框中:

from os import listdir

filepaths = [f for f in listdir("./data") if f.endswith('.csv')]
df = pd.concat(map(pd.read_csv, filepaths))

因为文件太多/太重而无法工作。

如果您知道其他解决方案,请提供帮助,

谢谢

编辑:

感谢您的回答,它似乎可以使用此代码:

for f in tqdm (listdir("E:\\Data\\Trades\\history")):
    if f.endswith('.csv'):
        pd.read_csv(f, 'rb').to_hdf('E:\\Data\\Trades\\hdf5_test.h5', key=f)

但我收到此错误FileNotFoundError: [Errno 2] No such file or directory: 'trade_20141123.csv' 这是列表中第一个文件的名称。

我在 jupyter 中也收到此警告:

ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.
  pd.read_csv(f, 'rb').to_hdf('E:\\Data\\Trades\\hdf5_test.h5', key=f)
C:\Users\Sam\anaconda3\envs\vaex_env\lib\site-packages\tables\path.py:155: NaturalNameWarning: object name is not a valid Python identifier: 'trade_20141122.csv'; it does not match the pattern ``^[a-zA-Z_][a-zA-Z0-9_]*$``; you will not be able to use natural naming to access this object; using ``getattr()`` will still work, though
  check_attribute_name(name)

我必须重命名所有文件吗?我不确定这是问题所在,但如果是什么字符问题呢?

干杯

【问题讨论】:

    标签: python pandas data-science hdf5


    【解决方案1】:

    不要使用列表推导。只需使用一个循环来读取、转换和写入每个文件,这样您就不会得到太多文件或内存不足。

    编辑 1:执行以下操作:

    for f in listdir("./data"):
        if f.endswith('.csv'):
            pd.read_csv(f).to_hdf(...)
    

    看看这个link

    编辑 2:尝试这样的事情:

    import numpy as np
    import pandas as pd
    import os, shutil, time, h5py
    
    root_dir = './data/'  # Unique results directory
    filepath = os.path.join(root_dir, 'file{0:03d}.csv')
    hdfpath = os.path.join(root_dir, 'results.h5')
    
    n_files = 10
    n_rows = 100
    n_cols = 10
    
    if True:
        # Clear previous results
        if os.path.isdir(root_dir):
            shutil.rmtree(root_dir)
            os.makedirs(root_dir)
        for i in range(n_files):
            print("write csv file:",i)
            results = np.random.random((n_rows, n_cols))
            np.savetxt(filepath.format(i), results, delimiter=',')
    
    # Convert the many csv files into a single hdf file
    start_time = time.time()
    
    for f in os.listdir("./data"):
        if f.endswith('.csv'):
           x='./data/'+f
           y='./data/'+f+'.hd5'
           df=pd.read_csv(x, 'rb',engine='python')
           df.to_hdf(y, key=f)
    
    print('%s seconds' % (time.time() - start_time))
    

    【讨论】:

    • 不知道如何在没有pandas的情况下转成hdf5,是这个意思吗?
    • 不,只是做一个显式循环:\pd.read_csv('input_file.csv').to_hdf('output_file.hdf5', key='data')"
    • 非常感谢您的帮助,如果您有时间我编辑了问题以添加我遇到的新问题,但如果您不知道您已经做了很多欢呼!
    • 谢谢,我试过了,它并没有真正为我工作,但我认为它接近我需要的,我会从 python 中休息一下,然后在一周左右回来我希望能发布对我有用的东西。非常感谢您的时间和帮助,非常感谢
    • 怎么会失败?
    猜你喜欢
    • 2016-12-13
    • 1970-01-01
    • 2014-07-08
    • 2014-06-13
    • 2019-08-07
    • 2017-05-20
    • 2021-05-03
    • 2018-05-23
    • 2019-12-02
    相关资源
    最近更新 更多