的hdf5
文件必須在table
format被寫入 爲了可查詢與pd.read_hdf
的where
參數(相對於fixed
格式)。
此外,A
必須declared as a data_column:
df.to_hdf('/tmp/out.h5', 'results_table', mode='w', data_columns=['A'],
format='table')
,或者指定所有的列(可查詢)的數據列:
df.to_hdf('/tmp/out.h5', 'results_table', mode='w', data_columns=True,
format='table')
那麼你可以使用
pd.read_hdf('/tmp/out.h5', 'results_table', where='A in [1,3,4]')
到選擇值列A
爲1,3或4的行例如,
import numpy as np
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2],
'B': [0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1],
'C': [34, 32, 35, 34, 31, 34, 29, 34, 12, 34, 32, 34],
'D': [11, 15, 22, 15, 9, 15, 11, 15, 14, 15, 13, 15]})
df.to_hdf('/tmp/out.h5', 'results_table', mode='w', data_columns=['A'],
format='table')
print(pd.read_hdf('/tmp/out.h5', 'results_table', where='A in [1,3,4]'))
產生
A B C D
0 1 0 34 11
2 3 1 35 22
3 4 1 34 15
5 1 0 34 15
7 3 0 34 15
8 4 1 12 14
10 1 0 32 13
如果你有一個很長的值,vals
的名單,那麼你可以使用字符串格式化來構成權where
說法:
where='A in {}'.format(vals)
感謝unutbu,對這個很好的答案只是一些評論。我明白,在答案開始時,你以表格格式將df寫入h5。然而,我的腳本的輸入是已經保存的h5,我怎麼知道它是否在正確的格式? – codeKiller
如果你的'h5'文件不是'table'格式,那麼使用帶'where'參數的'pd.read_hdf'會引發'TypeError:當從固定格式讀取時不能通過where規範...'。如果'h5'文件是''表'格式的'A'沒有被指定爲'data_column',那麼你會得到'ValueError:通過where表達式:A [1,3,4]包含一個無效變量參考...'。 – unutbu
我不知道將h5文件從'fixed'轉換爲'table'格式或者添加'data_columns'的快捷方式。據我所知,你必須將整個'h5'文件讀入一個DataFrame(或者使用'chunksize'參數以chunks的形式讀取),然後寫出或附加到另一個'h5'文件中'表格式。 – unutbu