2

我认为这对许多知道如何处理泡菜的人来说是基本的。但是,在尝试了几个小时后,我仍然不能很好地做到这一点。我有以下代码:

在第一个文件中

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)

第二个文件

我想加载我在第一个文件中的内容,并通过函数 name_model(record) 使一个人(即 John、Mary、Suzanne)的分数可调用:

import dill as pickle
B = pickle.load('name_model.pkl')

def name_model(record):
    if record in names:
        return(means.loc[record, 'score'])

这里显示了错误:

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'

我知道这个错误来自我对泡菜缺乏了解。我会虚心接受您的意见以改进此代码。谢谢!!

更新 我想实现的更具体的事情:

我希望能够使用我在第一个文件中编写的函数并将其转储,然后在第二个文件中读取它,并能够使用此函数查询记录中任何人的平均分数。

这是我所拥有的:

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"))  

当我执行这段代码时,我有这个错误File "test.py", line 13, in <module> B = name_score_function(record) NameError: name 'record' is not defined

我非常感谢您的帮助和耐心。

4

2 回答 2

8

谢谢你。看起来下面可以解决问题。

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"))
于 2016-07-20T14:32:13.847 回答
3

唔。您需要以与编写它相同的方式阅读它——将它嵌套在一个开放子句中:

import dill as pickle
with open('name_model.pkl' ,'rb') as f:
    B = pickle.load(f)
于 2016-07-19T00:58:56.890 回答