python 文本替换 'str' 对象不可调用

python text substitution 'str' object is not callable

我想替换表达式中的变量名。但是我得到了 str 不可调用的错误 这是我的例子

import numpy as np
import pandas as pd
raw_data = {'student_name': ['M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12'], 
        'vocal_grade': ['R', 'X', 'Y', 'Z', 'R', 'X', 'X', 'X', 'X', 'X', 'X', np.NaN]}
df = pd.DataFrame(raw_data, columns = ['student_name', 'vocal_grade'])

dict_sam_vocal = {'R': 8, 'X': 5, 'Y': 6, 'Z': 7}

这个很好用

x = 'vocal'
df[x+'_score'] = df[x+"_grade"].map(dict_sam_vocal)

当我尝试参数化字典时,出现以下错误

df[x+'_score'] = df[x+"_grade"].map("dict_sam_"+x)

pandas/src/inference.pyx in pandas.lib.map_infer (pandas/lib.c:63043)()

TypeError: 'str' object is not callable

问题是您将一个字符串传递给了 map,这在您的情况下需要字典。为了使地图将其视为字典而不是字符串,请使用 eval 评估字符串并取回相应的字典:

x = 'vocal'
df[x+'_score'] = df[x+"_grade"].map(eval("dict_sam_"+x))

您可以使用如下字符串调用 dict_sam_vocal

df[x+'_score'] = df[x+"_grade"].map(globals()["dict_sam_"+x])