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

使用DuckDB清洗数据集时SQL筛选条件失效问题求助

问题:DuckDB SQL过滤条件失效,目标排除值仍存在数据集内

我使用Python的DuckDB包清洗数据集,编写了以下SQL查询进行过滤:

dt = db.query(
    """
    select * 
    from dt_orig 
    where (A != '') and 
          (B != '' or B != 'Unknown' or B != 'Undefined') and
          (C != '') and
          (D != '' or D != '[UNKNOWN]')
    """
).df()

但通过以下Python代码检查字段A、B、C、D的唯一值时,发现本该被排除的行依然存在:

print("The unique A are", np.unique(dt['A']), ".")
print("The unique B are", np.unique(dt['B']), ".")
print("The unique C are", np.unique(dt['C']), ".")
print("The unique D are", np.unique(dt['D']), ".")

输出结果:

The unique A are ['A1' 'A2' 'A3' 'A4'] .

The unique B are ['' 'B1' 'Undefined' 'Unknown' 'B2'] .

The unique C are ['C1' 'C2' 'C3' 'C4'] .

The unique D are ['[UNKNOWN]' 'D1' 'D2' 'D3' 'D4'] .

问题根源与修正方案

你的过滤条件犯了逻辑错误:用OR连接的排除条件永远为真,导致过滤完全失效。

举个例子,针对字段B的条件B != '' or B != 'Unknown' or B != 'Undefined':

  • 当B的值是'Unknown'时,B != ''为真,整个OR条件就成立,这行数据会被保留;
  • 当B的值是''时,B != 'Unknown'为真,同样会被保留。

正确的逻辑应该是同时满足所有排除项都不匹配,也就是用AND替换OR,或者更简洁的用NOT IN语法:

修正后的SQL(两种写法任选其一)

写法1:用AND替换OR

dt = db.query(
    """
    select * 
    from dt_orig 
    where (A != '') and 
          (B != '' AND B != 'Unknown' AND B != 'Undefined') and
          (C != '') and
          (D != '' AND D != '[UNKNOWN]')
    """
).df()

写法2:用NOT IN简化条件

dt = db.query(
    """
    select * 
    from dt_orig 
    where (A != '') and 
          (B NOT IN ('', 'Unknown', 'Undefined')) and
          (C != '') and
          (D NOT IN ('', '[UNKNOWN]'))
    """
).df()

修正后重新执行查询,再检查唯一值,就能看到目标排除值已经被过滤掉了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:31:35