python - PyTables 从大型 CSV 中读取 block :

标签 python pandas numpy hdf5 pytables

我有以下代码,它从 CSV 读取数据并写入 PyTables。但是,pd.read_csv 创建一个数据框,而这在 PyTables 中不会处理。我该如何解决这个问题?我可以创建 numpy 数组,但这似乎太过分了,而且可能很耗时? (交易记录是我用正确的数据类型创建的类 - 如果使用 numpy,我必须复制它)

def get_transaction_report_in_chunks(transaction_file):
   transaction_report_data = pd.read_csv(transaction_file, index_col=None, parse_dates=False, chunksize=500000)
   return transaction_report_data

def write_to_hdf_from_multiple_csv(transaction_file_path):
   hdf = tables.open_file(filename='MyDB.h5', mode='a')
   transaction_report_table = hdf.create_table(hdf.root, 'Transaction_Report_Table_x', Transaction_Record, "Transaction Report Table")
   all_files = glob.glob(os.path.join(transaction_file_path, "*.csv"))
   for transaction_file in all_files:
       for transaction_chunk in get_transaction_report_in_chunks(transaction_file):
         transaction_report_table.append(transaction_chunk)
         transaction_report_table.flush()
  hdf.Close()

最佳答案

我会使用Pandas HDF Store ,这是 PyTables 底层非常方便的 API:

def write_to_hdf_from_multiple_csv(csv_file_path,
                                   hdf_fn='/default_path/to/MyDB.h5',
                                   hdf_key='Transaction_Report_Table_x',
                                   df_cols_to_index=True): # you can specify here a list of columns that must be indexed, i.e.: ['name', 'department']
    files = glob.glob(os.path.join(csv_file_path, '*.csv'))
    # create HDF file (AKA '.h5' or PyTables)
    store = pd.HDFStore(hdf_fn)
    for f in files:
        for chunk in pd.read_csv(f, 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()

关于python - PyTables 从大型 CSV 中读取 block :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41483285/

相关文章:

python - 在形态学打开和闭合产生相同结果的情况下?

python - 在 numpy 数组的元素之间插入零

python - 无法从pycharm导入numpy

python - 在不更改缩进或添加注释的情况下停用 python 中的代码

python - 设置对象实例变量的正确方法

python - Pandas :从行中的每个元素中减去行均值

python - 将多个 GluonTS 预测导出到 pandas 数据框

python - Pandas/python 并在数据框中使用带有日期的列

python - 将矩阵的行分配给新矩阵

python - 识别日期格式并将其更改为另一种格式