You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas DataFrame.query()时遭遇SyntaxError: EOL扫描字符串字面量错误

pandas DataFrame.query()多条件过滤报SyntaxError问题解决

使用pandas的DataFrame.query()编写多条件数据过滤语句时,出现SyntaxError: EOL while scanning string literal错误。短语句可正常执行,但添加更多过滤条件后触发报错,尝试三引号多行写法也未解决。

报错代码

data_normal = data.query('(total_area < 400) & (rooms < 10) & (living_area > 10) & (living_area < 200) \
        & (kitchen_area > 5) & (kitchen_area < 40) & (celling_height >= 2.5) & (last_price < 200000000) \ 
        & (last_price >= 1000000) & (floors_total < 30) & (days_exposition < 800) & (days_exposition > 5) \ 
        & (cityCenters_nearest <= 52000) & (parks_nearest <= 1500) & (parks_nearest > 10)')

正常运行的短语句

data_normal = data.query('(total_area < 400) & (rooms < 10) & (living_area > 10) & (living_area < 200) \
        & (cityCenters_nearest <= 52000) & (parks_nearest <= 1500) & (parks_nearest > 10)')

尝试的三引号写法

data_normal = data.query('''(total_area < 400) & (rooms < 10) & (living_area > 10) & (living_area < 200) \
        & (kitchen_area > 5) & (kitchen_area < 40) & (celling_height >= 2.5) & (last_price < 200000000) \ 
        & (last_price >= 1000000) & (floors_total < 30) & (days_exposition < 800) & (days_exposition > 5) \ 
        & (cityCenters_nearest <= 52000) & (parks_nearest <= 1500) & (parks_nearest > 10)''')

问题原因及解决方法

错误原因

报错的核心问题是行续符\后面存在空格。Python中使用\作为行续符时,后面不能有任何字符(包括空格),否则\会被视为普通字符,无法实现字符串的跨行延续,导致字符串提前结束,触发EOL while scanning string literal错误。

解决方案

有两种可行的修正方式:

方式1:移除行续符\后的空格

确保所有\后面直接换行,无任何空格:

data_normal = data.query('(total_area < 400) & (rooms < 10) & (living_area > 10) & (living_area < 200) \
        & (kitchen_area > 5) & (kitchen_area < 40) & (celling_height >= 2.5) & (last_price < 200000000) \
        & (last_price >= 1000000) & (floors_total < 30) & (days_exposition < 800) & (days_exposition > 5) \
        & (cityCenters_nearest <= 52000) & (parks_nearest <= 1500) & (parks_nearest > 10)')

方式2:使用三引号时去掉行续符\

三引号本身支持多行字符串,不需要额外加\转义,直接换行即可:

data_normal = data.query('''(total_area < 400) & (rooms < 10) & (living_area > 10) & (living_area < 200)
        & (kitchen_area > 5) & (kitchen_area < 40) & (celling_height >= 2.5) & (last_price < 200000000)
        & (last_price >= 1000000) & (floors_total < 30) & (days_exposition < 800) & (days_exposition > 5)
        & (cityCenters_nearest <= 52000) & (parks_nearest <= 1500) & (parks_nearest > 10)''')

内容的提问来源于stack exchange,提问作者Вадим Хибин

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:20:54