具有动态列名的pd.eval

2024-09-29 21:52:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在循环中的dataframe中生成新列,其中每个循环中的列名都是动态设置的,如果可能的话,我希望使用dataframe.eval()。例如:

for i in roll_windows_values:
    readFromColName = 'Movement _' + str(i)
    newColName = readFromColName + '_deviation'
    df[newColName] = df.eval('readFromColName.mean() - readFromColName')

这给了我一个错误

pandas.core.computation.ops.UndefinedVariableError: name 'readFromColName' is not defined

我还尝试将列名视为变量:

df[newColName] = df.eval('@readFromColName.mean() - @readFromColName')

但这给了我一个错误:


AttributeError: 'Load' object has no attribute '__name__'

有人知道如何从Dataframe.eval中的字符串变量中提取列名吗


Tags: nameindataframedfforwindows错误eval
2条回答

如果需要eval使用动态列名,可以相应地使用pd.eval执行此操作:

df[newColName] = pd.eval('df[readFromColName].mean() - df[readFromColName]')

请注意,顶级eval调用不需要@variable注释

为什么不使用f字串呢

df.eval(f'{readFromColName}.mean() - {readFromColName}')

相关问题 更多 >

    热门问题