2017-01-05 10 views
2

私はCSVから読み込んでPyTablesに書き込む次のコードを持っています。しかし、pd.read_csvはデータフレームを作成しますが、これはPyTablesでは処理されません。この問題をどうやって解決するのですか?私は素敵な配列を作成することができますが、これは殺し過ぎ、時間がかかる可能性がありますか? (トランザクション・レコードは、私が正しいデータ型で作成したクラスである - 私はnumpyのを使用している場合、これを複製する必要があり)PyTables大きなCSVをチャンクで読む:

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() 
+0

標準のPandas 'DataFrame.to_hdf()'や 'HDFStore.append'などを使用しないのには良い理由はありますか? – MaxU

+0

本当にありません。大規模なデータセットや特定の列のテーブルを照会するのに十分なのかどうかはわかりません。もう1つの問題は、クエリでメモリ内で計算できない結果が返された場合です。これをどのように処理するのかはわかりません。 – CodeGeek123

答えて

3

私はフードの下PyTablesのために非常にconvinient APIであるPandas HDF Storeを使用します。

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() 
+0

ありがとうございます。どのように私は列が取るべきデータ型を指定するのですか?私はクラス/ dictを渡すことができます。私はこれを見る方法もありますか? Pytablesでは – CodeGeek123

+0

@ CodeGeek123を表示できますが、dtypesを指定する必要はありません。これはDF列dtypesから継承されます。そして 'store = pd.HDFStore( '/ path/to/file_name.h5'); print(store.get_storer( 'your_hdf_key')。table) 'は、dtype、インデックスなどの詳細をすべて与える必要があります。 – MaxU

関連する問題