我有一个有2列(ID,内容)的数据帧,我以pickle
格式保存.例如,我有10行(即0到9 ID).我试图通过从pickle file without loading the entire file传递ID
(有效ID介于0-9之间)来加载单行.
import pandas as pd
import pickle
id = 2
path = "contents.pickle"
# dummy data
df = pd.DataFrame({
"ID": [0,1,2,3,4,5,6,7,8,9],
"Contents": [0,1,2,3,4,5,6,7,8,9]
})
print(f"{df=}")
df.to_pickle(path=path)
df = pd.read_pickle(filepath_or_buffer=path)
with open(path, "rb") as handle:
df = pickle.load(handle)
以上两者都是一次性读取所有数据.我没有得到我应该通过ID
来加载那一行的位置.如果dataframe
不可能,我try 了简单的list
,其中包含使用引用here保存在PICLE文件中的数据,但失败了.
data = [0,1,2,3,4,5,6,7,8,9]
with open(path, "wb") as handle:
pickle.dump(data, handle)
file = open(file=path)
file.seek(id)
row = pickle.load(file)
print(f"{row=}")