PyTables, прочитанные из большого CSV-кода:

У меня есть следующий код, который читает из CSV и пишет в PyTables. Однако pd.read_csv создает фрейм данных, и это не обрабатывается в PyTables. Как мне решить эту проблему? Я могу создавать массивы numpy, но это похоже на убийство и, возможно, отнимает много времени? (Transaction Record - это класс, который я создал с правильными типами данных - я должен повторить это, используя 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()

1 ответ

Решение

Я бы использовал Pandas HDF Store, очень удобный API для PyTables:

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()
Другие вопросы по тегам