【问题标题】:python text substitution 'str' object is not callablepython文本替换'str'对象不可调用
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以使用这样的字符串调用dict_sam_vocal

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-09
      • 2015-06-07
      • 2019-07-10
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多