【问题标题】:PyTables Read From Large CSV in chunks :PyTables 从大 CSV 中读取块:
【发布时间】:2017-05-19 21:26:01
【问题描述】:

我有以下代码从 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 DataFrame.to_hdf()HDFStore.append 等?
  • 并非如此。我只是不确定这对于大型数据集和查询特定列上的表是否足够好。另一个问题是,如果查询返回的结果无法在内存中计算,我不确定我将如何处理?

标签: python pandas numpy hdf5 pytables


【解决方案1】:

我会使用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()

【讨论】:

  • 谢谢。我如何指定列应该采用的数据类型 - 我可以传递一个类/字典吗?还有一种方法可以查看吗?使用 Pytables,您可以查看
  • @CodeGeek123,您不必指定 dtypes - 它将从 DF 列 dtypes 继承。 store = pd.HDFStore('/path/to/file_name.h5'); print(store.get_storer('your_hdf_key').table) 应该提供关于 dtypes、indexes 等的所有详细信息。
猜你喜欢
  • 1970-01-01
  • 2018-04-14
  • 2014-01-29
  • 1970-01-01
  • 2022-08-19
  • 2018-11-01
  • 2013-05-06
相关资源
最近更新 更多