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

搜索Excel指定列匹配列表值提取整行时pandas和openpyxl报错求助

报错根因

  1. TypeError: 'Series' objects are mutable, thus they cannot be hashed:是由于Day列存在非标量值(如单元格合并、空值被解析为复杂类型、列数据含嵌套Series),无法进行哈希校验导致isin判断失败。
  2. 两次出现ValueError: The truth value of a Series is ambiguous:是运行后续代码时未清空环境变量,残留了pandas读取的sheet对象,循环逻辑实际作用于pandas的Series结构而非openpyxl的行对象导致。

Pandas 实现方案(推荐)

import pandas as pd

# 配置参数
mylist = ['Monday', 'Wednesday', 'Thursday']
source_file = r'替换为你的源Excel文件路径'
output_file = r'匹配结果.xlsx'

# 读取文件时指定Day列为字符串类型,避免自动解析异常
df = pd.read_excel(source_file, dtype={'Day': str})

# 先去除Day列值前后空格,再做匹配筛选
filtered_df = df[df['Day'].str.strip().isin(mylist)]

# 导出结果,不保留pandas自动生成的索引
filtered_df.to_excel(output_file, index=False)

# 控制台打印验证
print(filtered_df)

Openpyxl 实现方案

from openpyxl import load_workbook
from openpyxl import Workbook

# 配置参数
mylist = ['Monday', 'Wednesday', 'Thursday']
source_file = r'替换为你的源Excel文件路径.xlsx'
output_file = r'匹配结果.xlsx'

# 读取源文件,data_only=True表示直接读取单元格值而非公式
wb = load_workbook(source_file, data_only=True)
ws = wb.active

# 新建结果工作簿
new_wb = Workbook()
new_ws = new_wb.active

# 复制表头到新文件
header = [cell.value for cell in ws[1]]
new_ws.append(header)

# 从第二行开始遍历所有数据行,values_only=True直接获取单元格值
for row in ws.iter_rows(min_row=2, values_only=True):
    day_val = str(row[0]).strip()
    if day_val in mylist:
        new_ws.append(row)

# 保存结果文件
new_wb.save(output_file)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:45:01