2017-09-13 659 views
4

我有大型熊貓DataFrame與財務數據。 我沒有問題附加和連接到我的.h5文件的額外的列和數據框。用Pandas,Python追加數據到HDF5文件

財務數據每分鐘都在更新一次,我需要每分鐘向我的.h5文件中的所有現有表添加一行數據。

這是我到目前爲止所嘗試的,但無論我做什麼,它都會覆蓋.h5文件,並且不會追加數據。

HDFStore方式:

#we open the hdf5 file 
save_hdf = HDFStore('test.h5') 

ohlcv_candle.to_hdf('test.h5') 

#we give the dataframe a key value 
#format=table so we can append data 
save_hdf.put('name_of_frame',ohlcv_candle, format='table', data_columns=True) 

#we print our dataframe by calling the hdf file with the key 
#just doing this as a test 
print(save_hdf['name_of_frame'])  

我已經嘗試過的另一種方式,to_hdf:

#format=t so we can append data , mode=r+ to specify the file exists and 
#we want to append to it 
tohlcv_candle.to_hdf('test.h5',key='this_is_a_key', mode='r+', format='t') 

#again just printing to check if it worked 
print(pd.read_hdf('test.h5', key='this_is_a_key')) 

這裏是什麼DataFrames的一個看起來像被read_hdf後:

  time  open  high  low close  volume   PP 
0 1505305260 3137.89 3147.15 3121.17 3146.94 6.205397 3138.420000 
1 1505305320 3146.86 3159.99 3130.00 3159.88 8.935962 3149.956667 
2 1505305380 3159.96 3160.00 3159.37 3159.66 4.524017 3159.676667 
3 1505305440 3159.66 3175.51 3151.08 3175.51 8.717610 3167.366667 
4 1505305500 3175.25 3175.53 3170.44 3175.53 3.187453 3173.833333 

下一次我得到數據(每分鐘)時,我想將它的一行添加到所有列的索引5中。然後是6和7 ..等等,而不必讀取和操作整個文件在內存中,因爲這將打敗這一點。 如果有更好的解決方法,不要羞於推薦它。

P.S.對不起,這裏的表格格式在這裏

回答

2

pandas.HDFStore.put()有參數append(默認爲False) - 指示熊貓覆蓋而不是附加。

那麼試試這個:

store = pd.HDFStore('test.h5') 

store.append('name_of_frame', ohlcv_candle, format='t', data_columns=True) 

我們也可以使用store.put(..., append=True),但該文件也應以表格形式創建:

store.put('name_of_frame', ohlcv_candle, format='t', append=True, data_columns=True) 
+0

就是它,非常感謝你的快速回答! – Karl

+0

@Karl,很高興我可以幫助:) – MaxU

+0

你可以添加一些解釋爲什麼'append'工作和'put'不? – Mayou36