You need to enable JavaScript to run this app. 如何修复Pandas query中‘AnnAssign’ nodes are not implemented错误?
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Pandas query中‘AnnAssign’ nodes are not implemented错误?

Pandas query处理含冒号列名的报错问题

问题场景

以下代码可正常运行:

import pandas as pd
d = {'col1': [1, 7, 3, 6], 'col2': [3, 4, 9, 1]}
df = pd.DataFrame(data=d)

out = df.query('col1 > col2')

运行结果:

col1  col2
1     7     4
3     6     1

但将列名col1修改为col1:suf后,执行代码会报错:

d = {'col1:suf': [1, 7, 3, 6], 'col2': [3, 4, 9, 1]}
df = pd.DataFrame(data=d)

out = df.query('col1:suf > col2')

错误信息:'AnnAssign' nodes are not implemented

提问:除了重命名列之外,是否有简便方法避免该问题?

解决方案

冒号在query的表达式语法中会被解析为类型注解相关的语法,导致列名识别失败。无需重命名列,可通过以下两种方式解决:

  • 用反引号包裹含特殊字符的列名:这是最简洁的处理方式,明确告诉query这是一个列名而非语法元素:
out = df.query('`col1:suf` > col2')
  • 通过@符号引用DataFrame并索引列:借助@将外部变量(这里是DataFrame本身)引入查询表达式,再用索引访问列:
out = df.query('@df["col1:suf"] > col2')

两种方法执行后都能得到预期结果:

col1:suf  col2
1         7     4
3         6     1

内容的提问来源于stack exchange,提问作者Bugger_man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:15:31