迭代Pandas DataFrame行按值类型生成查询条件的实现方法
实现代码
import pandas as pd import numpy as np # 构造示例DataFrame df = pd.DataFrame({ 'A': [0, 1, 34, 11], 'B': [11, 0, 1, np.nan], 'C': [[13,16,18], np.nan, [13,16], [10,16]] }, index=[1,2,3,4]) # 存储每行生成的查询语句,格式为(行索引, 查询语句) query_result = [] for idx in df.index: # 过滤当前行的空值列 line = df.loc[idx].dropna() conds = [] for col, val in line.items(): if isinstance(val, list): # 处理列表类型字段,生成in条件 list_content = ', '.join(map(str, val)) conds.append(f"`{col}` in ({list_content})") else: # 处理数值类型字段,生成等于条件 conds.append(f"`{col}`=={int(val)}") # 拼接所有条件 full_query = ' and '.join(conds) query_result.append((idx, full_query)) print(f"索引{idx}生成的查询语句:{full_query}")
运行输出
索引1生成的查询语句:`A`==0 and `B`==11 and `C` in (13, 16, 18) 索引2生成的查询语句:`A`==1 and `B`==0 索引3生成的查询语句:`A`==34 and `B`==1 and `C` in (13, 16) 索引4生成的查询语句:`A`==11 and `C` in (10, 16)
逻辑说明
- 每行处理前先调用
dropna()过滤空值列,无需处理nan对应的字段 - 无需单独判断行内是否存在list类型值,直接遍历每个字段的类型生成对应条件,最后统一用
and拼接即可,逻辑更简洁通用 - 列表类型字段先将元素转成字符串后用逗号拼接,再套入
in语法模板;数值类型直接转int后套入等于语法模板
内容的提问来源于stack exchange,提问作者Atefe Nematolahi
相关产品推荐
相关产品推荐

