首页 > 解决方案 > 将数百个 csv 文件转换为 hdf5 文件

问题描述

我找到了很多关于这个问题的答案,但没有找到我具体想做的事情。我有很多 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)

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

干杯

标签: pythonpandasdata-sciencehdf5

解决方案


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

编辑1:做类似的事情:

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

看看这个链接

编辑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))

推荐阅读