我有大型pandas DataFrames与财务数据。我没有问题附加和连接其他列和DataFrames到我的.h5文件。
财务数据每分钟都在更新,我需要每分钟向我的.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'))
以下是read_hdf之后的一个DataFrame:
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 ..依此类推,而无需读取和操作整个文件因为这会破坏这样做的记忆。如果有更好的解决方法,不要害羞推荐它。
PS抱歉在这里格式化该表
发布于 2018-09-25 09:31:41
pandas.HDFStore.put()有参数append
(默认为False
) - 指示Pandas覆盖而不是追加。
所以试试这个:
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)
发布于 2018-09-25 10:30:12
tohlcv_candle.to_hdf('test.h5',key='this_is_a_key', append=True, mode='r+', format='t')
您需要传递另一个参数append=True
来指定将数据附加到现有数据(如果在该键下找到),而不是覆盖它。
如果没有这个,默认值是False
,如果遇到现有的表,'this_is_a_key'
则覆盖它。
该mode=
参数仅在文件级别,告知是否要覆盖或附加整个文件。
一个文件可以有任意数量的键,因此mode='a', append=False
设置将意味着只有一个键被覆盖而其他键保持不变。
我有与您相似的经历,并在参考文档中找到了额外的附加参数。设置完成后,现在它正好适合我。
参考:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_hdf.html
注意:hdf5不会为数据帧的索引做任何事情。我们需要在将数据放入或放出数据之前解决这些问题。
https://stackoverflow.com/questions/-100002716
复制相似问题