我想将函数应用于数据框,但更改该函数中使用的参数。我想:
我的实际代码更复杂,有更多参数和更复杂的计算以及各种输出,但这显示了原则:
>>> parameters_df # these are the parameters that I want to loop through
a b c mean_output # (this is what I want to calculate)
1 2 3
1 3 5
>>> calc_df
name category score # output(this is what I want to calculate)
John a 50
Jill c 60
Jenny b 70
Jeff a 80
这是我的代码:
def set_parameters(row):
parameter_dict = {a: row['a'], 1:row['b'], 2:row['c']}
parameter_df['output'] = parameter_df.apply(calc, axis=1)
return parameter_df['output'].mean(axis = 1)
def calc(row):
output = parameter_dict[row['parameter_df']] * 2
return output
parameters_df['mean_score'] = parameters_df.apply(set_parameters, axis = 1)
但是我得到了这个错误代码:
(“名称'parameter_dict'未定义”,'发生在索引0','发生在索引0')
就像执行calc函数一样,它找不到我在set_parameters函数中定义的参数字典,即使set参数在计算中使用了calc函数。
我做错了什么?
答案 0 :(得分:0)
您没有在两个函数之间传递变量。你需要:
def set_parameters(row):
parameter_dict = {a: row['a'], 1:row['b'], 2:row['c']}
parameter_df['output'] = parameter_df.apply(calc, args=(parameter_dict,), axis=1)
return parameter_df['output'].mean(axis = 1)
def calc(row, parameter_dict):
output = parameter_dict[row['parameter_df']] * 2
return output