3 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
我將使用HDF5 / pytables如下:
將數(shù)據(jù)盡可能長地保留為python列表。
將結(jié)果追加到該列表。
當(dāng)它變大時(shí):
使用pandas io(和一個(gè)可附加的表)推送到HDF5 Store。
清除列表。
重復(fù)。
實(shí)際上,我定義的函數(shù)為每個(gè)“鍵”使用一個(gè)列表,以便您可以在同一過程中將多個(gè)DataFrame存儲到HDF5存儲。
我們定義一個(gè)函數(shù),您需要在每一行中調(diào)用它d
:
CACHE = {}
STORE = 'store.h5' # Note: another option is to keep the actual file open
def process_row(d, key, max_len=5000, _cache=CACHE):
"""
Append row d to the store 'key'.
When the number of items in the key's cache reaches max_len,
append the list of rows to the HDF5 store and clear the list.
"""
# keep the rows for each key separate.
lst = _cache.setdefault(key, [])
if len(lst) >= max_len:
store_and_clear(lst, key)
lst.append(d)
def store_and_clear(lst, key):
"""
Convert key's cache list to a DataFrame and append that to HDF5.
"""
df = pd.DataFrame(lst)
with pd.HDFStore(STORE) as store:
store.append(key, df)
lst.clear()
注意:我們使用with語句在每次寫入后自動關(guān)閉存儲。它可以更快地保持開放,但即便如此我們建議您定期刷新(收盤刷新)。還要注意,使用collection deque而不是列表可能更易讀,但是列表的性能在這里會稍好一些。
要使用此功能,請致電:
process_row({'time' :'2013-01-01 00:00:00', 'stock' : 'BLAH', 'high' : 4.0, 'low' : 3.0, 'open' : 2.0, 'close' : 1.0},
key="df")
注意:“ df”是pytables存儲中使用的存儲鍵。
作業(yè)完成后,請確保您store_and_clear剩余的緩存:
for k, lst in CACHE.items(): # you can instead use .iteritems() in python 2
store_and_clear(lst, k)
現(xiàn)在,您可以通過以下方式使用完整的DataFrame:
with pd.HDFStore(STORE) as store:
df = store["df"] # other keys will be store[key]

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
您實(shí)際上是在嘗試解決兩個(gè)問題:捕獲實(shí)時(shí)數(shù)據(jù)并分析該數(shù)據(jù)。第一個(gè)問題可以通過為此目的設(shè)計(jì)的Python日志記錄來解決。然后可以通過讀取相同的日志文件來解決另一個(gè)問題。
添加回答
舉報(bào)