如何为DataFrame的loc()设置多条件?筛选结果不符预期求解
排查方法及修正建议
检查Section列的字符串格式
很多时候是字符串存在空格、大小写差异或特殊字符导致匹配失败,比如' group1'或'Group1'。先查看列的唯一值确认:print(df['Section'].unique())若存在格式问题,先清洗数据后再筛选:
df['Section'] = df['Section'].str.strip().str.lower() df2 = df.loc[((df.CustID == i) & (df['Section'].isin(['group1', 'group2']))), ['CustID', 'Section']].copy()验证CustID与i的类型匹配
如果i是整数但df.CustID是字符串类型(如'123'),==判断会返回错误结果。打印类型和当前值确认:print(f"i的值: {i}, 类型: {type(i)}") print(f"CustID列类型: {df['CustID'].dtype}")类型不匹配时做转换,比如将CustID转为整数:
df['CustID'] = df['CustID'].astype(int)单独验证每个筛选条件
拆分条件单独测试,确认每个条件的匹配结果是否符合预期:# 检查CustID匹配行数 cust_match = (df.CustID == i).sum() # 检查Section匹配行数 section_match = df['Section'].isin(['group1', 'group2']).sum() # 检查组合条件匹配行数 combined_match = ((df.CustID == i) & df['Section'].isin(['group1', 'group2'])).sum() print(f"CustID匹配行数: {cust_match}, Section匹配行数: {section_match}, 组合匹配行数: {combined_match}")如果组合匹配行数异常,就能定位是单个条件的问题。
重置索引排除数据异常
若DataFrame存在重复索引或未刷新的修改痕迹,可能导致筛选逻辑异常,重置索引后再尝试:df = df.reset_index(drop=True) df2 = df.loc[((df.CustID == i) & (df['Section'].isin(['group1', 'group2']))), ['CustID', 'Section']].copy()
内容的提问来源于stack exchange,提问作者PandaSmanda18
相关产品推荐
相关产品推荐

