如何在循环中多条件过滤DataFrame并生成多结果DataFrame
多列唯一值组合过滤DataFrame并导出Excel方案
核心思路
要实现任意列数的唯一值组合过滤,关键是生成所有列唯一值的笛卡尔积(即所有可能的组合),再针对每个组合构建多条件过滤逻辑,筛选对应行后导出。
具体实现步骤
提取指定列的唯一值
先从原DataFrame中提取目标列的唯一值,整理成字典(和你现有的data格式一致),如果还没实现这一步,可用以下代码生成:import pandas as pd from itertools import product # df为原DataFrame,target_cols是指定的列名列表,比如['OS', 'Work'] target_cols = ['OS', 'Work'] data = {col: set(df[col].unique()) for col in target_cols}生成所有唯一值组合
使用itertools.product生成各列唯一值的笛卡尔积,自动适配任意列数:# 将集合转为列表,用于生成笛卡尔积 values_list = [list(data[col]) for col in target_cols] # 生成所有组合,每个组合是元组,比如('IOS', 'Developer') all_combinations = product(*values_list)遍历组合并过滤导出
对每个组合构建多条件过滤,筛选后导出Excel:save_path = "./output/" # 你的导出路径 for combo in all_combinations: # 叠加多列过滤条件 filter_condition = pd.Series([True]*len(df), index=df.index) for col, val in zip(target_cols, combo): filter_condition &= (df[col] == val) # 筛选符合条件的行 filtered_df = df[filter_condition] # 生成可区分的文件名 filename = "_".join(combo) + ".xlsx" full_path = save_path + filename # 导出Excel(替换为你已有的导出逻辑即可) filtered_df.to_excel(full_path, index=False)
简化写法(用query语法)
如果偏好更简洁的代码,可使用df.query()构建过滤条件:
for combo in all_combinations: # 拼接query字符串,比如"OS == 'IOS' and Work == 'Developer'" query_str = " and ".join([f"{col} == '{val}'" for col, val in zip(target_cols, combo)]) filtered_df = df.query(query_str) # 导出逻辑同上 filename = "_".join(combo) + ".xlsx" filtered_df.to_excel(save_path + filename, index=False)
内容的提问来源于stack exchange,提问作者Joaquin Hernandez
相关产品推荐
相关产品推荐

