将 Pandas 数据帧存储在工作内存中

Dea*_*een 2 python binaryfiles pandas

有什么方法可以获取数据框,例如

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
Run Code Online (Sandbox Code Playgroud)

并将其作为二进制对象存储在临时内存中,然后可以使用

open(df, 'rb')
Run Code Online (Sandbox Code Playgroud)

那么,与其做类似的事情

open('/home/user/data.csv', 'rb')
Run Code Online (Sandbox Code Playgroud)

代码是

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

df_rb = *command to store in temp working memory as binary readable*

open(df_rb, 'rb')
Run Code Online (Sandbox Code Playgroud)

wwi*_*wii 5

您可以将其 pickle 为内存中的 io.BytesIO 对象

import pandas as pd
import pickle, io
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
f = io.BytesIO()
pickle.dump(df,f)
f.seek(0)    # necessary to start reading at the beginning of the "file"
dg = pickle.load(f)

In [48]: dg==df
Out[48]: 
      a     b
0  True  True
1  True  True
2  True  True
Run Code Online (Sandbox Code Playgroud)