python文本替换“str”对象不是callab

2024-09-28 19:20:08 发布

您现在位置: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}

这个很好用

^{pr2}$

当我试图参数化dictionary时,我得到以下错误

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

Tags: nameimportpandasdfdatarawas错误
2条回答

问题是您向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])

相关问题 更多 >