【发布时间】:2016-07-04 21:58:21
【问题描述】:
我想在表达式中替换一个变量名。但是我收到 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是一个字符串。字符串的内容可能与函数的名称相同,但不会以任何方式将其连接到函数
标签: python string dictionary text substitution