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

如何按筛选条件将DataFrame拆分至两个Excel文件

修正DataFrame拆分Excel的代码问题

原代码的问题点

  • iterrows()遍历返回的row是行数据对象,不是行索引,data.at[row, 'cheese 1']的索引用法完全错误,应该通过row['cheese 1']直接取单元格值,或者用index作为行索引。
  • 条件判断里的|是位运算符,不是逻辑或,应该用or;而且pattern in 单元格值只能检查完整字符串匹配,无法实现“包含任意目标词”的需求。
  • 循环里用data.at[row:].to_excel()会重复写入大量重复数据,效率极低,完全没必要逐行处理。

正确实现代码

import pandas as pd

# 示例数据(如果已有data可跳过这部分)
data = pd.DataFrame({
    'cheese 1': ['blue', 'mozzarella', 'maccagno', 'brie'],
    'cheese 2': ['mozzarella', 'munster', 'mozzarella', 'berkswell'],
    'cheese 3': ['camembert', 'edam', 'ricotta', 'parmigiano']
})

# 定义要匹配的关键词模式
pattern = r'blue|mozzarella'

# 生成布尔掩码:检查cheese 1或cheese 2列是否包含目标词
# case=False表示忽略大小写,不需要可删除
mask = data['cheese 1'].str.contains(pattern, case=False) | data['cheese 2'].str.contains(pattern, case=False)

# 拆分DataFrame
included_df = data[mask]  # 任意一列包含目标词的行
excluded_df = data[~mask] # 两列都不包含目标词的行

# 写入Excel文件,用with语句自动管理文件资源
with pd.ExcelWriter('./Included cheese.xlsx', engine='xlsxwriter') as writer:
    included_df.to_excel(writer, index=False)  # index=False不写入行索引

with pd.ExcelWriter('./Excluded cheese.xlsx', engine='xlsxwriter') as writer_2:
    excluded_df.to_excel(writer_2, index=False)

代码说明

  • 用str.contains直接对整列做正则匹配,比逐行循环效率高得多,一次就能生成所有符合条件的行的掩码。
  • 通过布尔掩码直接拆分DataFrame,逻辑清晰且避免重复写入。
  • with语句会自动关闭ExcelWriter,无需手动处理文件关闭操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:06:24