2016-07-04 57 views
0

我想在表達式中替換變量名稱。但是我得到的錯誤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 
+0

'.map()'將函數作爲參數。 ''dict_sam _「+ x'是一個字符串。該字符串的內容可能與函數的名稱相同,但不以任何方式將其連接到該函數 –

回答

0

問題是你傳遞了一個字符串到map,這個字符串在你的案例中正在期待一個字典。爲了使地圖把它當作一本字典,而不是一個字符串,使用eval評估串並取回相應的字典:

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

您可以使用一個字符串這樣叫dict_sam_vocal

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