我想在表達式中替換變量名稱。但是我得到的錯誤str是不可呼叫 這裏是我的榜樣python文本替換'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()'將函數作爲參數。 ''dict_sam _「+ x'是一個字符串。該字符串的內容可能與函數的名稱相同,但不以任何方式將其連接到該函數 –