python - 使用 Pandas、Python 将数据附加到 HDF5 文件

标签 python pandas dataframe hdf5

我有包含财务数据的大型 pandas DataFrames。 我可以毫无问题地将额外的列和 DataFrame 附加和连接到我的 .h5 文件。

财务数据每分钟更新一次,我需要每分钟向 .h5 文件中的所有现有表追加一行数据。

这是我到目前为止尝试过的方法,但无论我做什么,它都会覆盖 .h5 文件,而不仅仅是附加数据。

HDF存储方式:

#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'))

这是其中一个 DataFrame 在被 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 ……等等,而不必读取和操作内存中的整个文件,因为那样会破坏这样做的意义。 如果有更好的方法来解决这个问题,请不要羞于推荐。

附言抱歉这里的表格格式

最佳答案

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)

注意: 附加仅适用于 table(format='t' - 是 format='table 的别名') 格式。

关于python - 使用 Pandas、Python 将数据附加到 HDF5 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46206125/

相关文章:

python - 为 IPython 创建 PySpark 配置文件

python - 如何在 dataframegroup python 中找到具有重复值的组列?

python:删除 Pandas 数据框中包含字符串的所有行

python - pandas loc 具有多个 or 条件

python - Pandas - 添加一列以在 group-by 后唯一标识每个组

python - 将两个数据框合并到一个公共(public)索引上(无需创建单独的行)

python - 如何将大量参数传递给 **kwargs

Python cx_oracle 通过位置绑定(bind)变量忽略数字

python - 前向填充 python pandas 数据框中除最后一个值外的所有内容

python - 合并来自 Github 存储库链接的所有 csv 文件,使其成为一个 csv 文件