ach*_*low 1 python pickle pandas dill
我认为这对许多知道如何处理泡菜的人来说是基础。但是,我尝试了几个小时后仍然无法完全正确。我有以下代码:
在第一个文件中
import pandas as pd
names = ["John", "Mary", "Mary", "Suzanne", "John", "Suzanne"]
scores = [80, 90, 90, 92, 95, 100]
records = pd.DataFrame({"name": names, "score": scores})
means = records.groupby('name').mean()
def name_score_function(record):
if record in names:
return(means.loc[record, 'score'])
import dill as pickle
with open('name_model.pkl', 'wb') as file:
pickle.dump(means, file)
Run Code Online (Sandbox Code Playgroud)
第二个文件
我想加载第一个文件中的内容,并通过函数 name_model(record) 使一个人(即约翰、玛丽、苏珊娜)的分数可调用:
import dill as pickle
B = pickle.load('name_model.pkl')
def name_model(record):
if record in names:
return(means.loc[record, 'score'])
Run Code Online (Sandbox Code Playgroud)
这里显示错误:
File "names.py", line 21, in <module>
B = pickle.load('name_model.pkl')
File "/opt/conda/lib/python2.7/site-packages/dill/dill.py", line 197, in load
pik = Unpickler(file)
File "/opt/conda/lib/python2.7/site-packages/dill/dill.py", line 356, in __init__
StockUnpickler.__init__(self, *args, **kwds)
File "/opt/conda/lib/python2.7/pickle.py", line 847, in __init__
self.readline = file.readline
AttributeError: 'str' object has no attribute 'readline'
Run Code Online (Sandbox Code Playgroud)
我知道错误来自我对泡菜缺乏了解。我虚心接受您的意见以改进此代码。谢谢!!
更新 我想实现的更具体的事情:
我希望能够使用我在第一个文件中编写的函数并将其转储,然后在第二个文件中读取它并能够使用此函数查询记录中任何人的平均分数。
这是我所拥有的:
import pandas as pd
names = ["John", "Mary", "Mary", "Suzanne", "John", "Suzanne"]
scores = [80, 90, 90, 92, 95, 100]
records = pd.DataFrame({"name": names, "score": scores})
means = records.groupby('name').mean()
def name_score_function(record):
if record in names:
return(means.loc[record, 'score'])
B = name_score_function(record)
import dill as pickle
with open('name_model.pkl', 'wb') as file:
pickle.dump(B, file)
with open('name_model.pkl', 'rb') as file:
B = pickle.load(f)
def name_model(record):
return B(record)
print(name_model("John"))
Run Code Online (Sandbox Code Playgroud)
当我执行此代码时,出现此错误 File "test.py", line 13, in <module>
B = name_score_function(record)
NameError: name 'record' is not defined
我非常感谢您的帮助和耐心。
谢谢你。看起来以下可以解决问题。
import pandas as pd
names = ["John", "Mary", "Mary", "Suzanne", "John", "Suzanne"]
scores = [80, 90, 90, 92, 95, 100]
records = pd.DataFrame({"name": names, "score": scores})
means = records.groupby('name').mean()
import dill as pickle
with open('name_model.pkl', 'wb') as file:
pickle.dump(means, file)
with open('name_model.pkl', 'rb') as file:
B = pickle.load(file)
def name_score_function(record):
if record in names:
return(means.loc[record, 'score'])
print(name_score_function("John"))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16861 次 |
最近记录: |