2015-10-31 42 views
6

我有一個巨大的HDF5文件,我想加載它的一部分在一個熊貓DataFrame中執行一些操作,但我有興趣過濾一些行。用條件讀取HDF5文件到熊貓DataFrame

我可以解釋用一個例子更好:

原始HDF5文件看起來是這樣的:

A B C D 
1 0 34 11 
2 0 32 15 
3 1 35 22 
4 1 34 15 
5 1 31 9 
1 0 34 15 
2 1 29 11 
3 0 34 15 
4 1 12 14 
5 0 34 15 
1 0 32 13 
2 1 34 15 
etc etc etc etc 

我所試圖做的是加載此,正是因爲它是一個熊貓據幀,但只有where A==1 or 3 or 4

到現在爲止,我可以只使用加載整個HDF5:

store = pd.HDFStore('Resutls2015_10_21.h5') 
df = pd.DataFrame(store['results_table']) 

我看不到如何在這裏包含where條件。

回答

6

hdf5文件必須在table format被寫入 爲了可查詢與pd.read_hdfwhere參數(相對於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) 
+0

感謝unutbu,對這個很好的答案只是一些評論。我明白,在答案開始時,你以表格格式將df寫入h5。然而,我的腳本的輸入是已經保存的h5,我怎麼知道它是否在正確的格式? – codeKiller

+0

如果你的'h5'文件不是'table'格式,那麼使用帶'where'參數的'pd.read_hdf'會引發'TypeError:當從固定格式讀取時不能通過where規範...'。如果'h5'文件是''表'格式的'A'沒有被指定爲'data_column',那麼你會得到'ValueError:通過where表達式:A [1,3,4]包含一個無效變量參考...'。 – unutbu

+0

我不知道將h5文件從'fixed'轉換爲'table'格式或者添加'data_columns'的快捷方式。據我所知,你必須將整個'h5'文件讀入一個DataFrame(或者使用'chunksize'參數以chunks的形式讀取),然後寫出或附加到另一個'h5'文件中'表格式。 – unutbu

1

您可以使用pandas.read_hdfhere)和可選參數where來完成此操作。
對於exampleread_hdf('store_tl.h5', 'table', where = ['index>2'])

+0

謝謝Dean,是否可以包含更復雜的條件?例如,如果我的A列的值爲1到100,我想選擇一些隨機的東西,如[1,3,11,16,27,33,34,44,41,55,68,70,77,81 ,90] ...我在問,因爲在主要問題中,我想簡化它,但在我的實際情況中,where條件需要更復雜 – codeKiller

+0

找到需要傳遞給Expr的文檔其中:http://nullege.com/codes/search/pandas.computation.pytables.Expr?fulldoc=1(這可能會有幫助,但我沒有看到通過遏制過濾的選項) –

+0

好的,非常感謝 – codeKiller