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

使用Pandas 0.24.2压缩CSV为Zip时遇TypeError: unhashable type: 'dict'

解决Pandas 0.24.2导出压缩CSV时的TypeError问题

错误原因

Pandas 0.24.2的to_csv方法里,compression参数仅支持字符串类型(比如'zip'),不接受字典形式的配置。你传入的字典{"method": "zip", "archive_name": f'report.csv'}会触发unhashable type: 'dict'错误——因为底层代码会尝试把这个字典当作键去匹配预定义的压缩映射表,而字典是不可哈希的类型,无法完成这个操作。

解决方案

方案1:不升级Pandas,手动压缩

如果无法升级版本,先导出普通CSV,再用Python内置的zipfile模块手动打包:

import zipfile

# 导出未压缩的CSV文件
csv_path = '../file location/report.csv'
df.to_csv(csv_path)

# 手动打包成zip
zip_path = '../file location/report.csv.zip'
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zip_handler:
    zip_handler.write(csv_path, arcname='report.csv')  # arcname设置压缩包内的文件名

方案2:升级Pandas到支持字典参数的版本

从Pandas 0.25.0开始,to_csv的compression参数支持传入字典配置压缩细节(包括指定archive_name)。先执行升级命令:

pip install --upgrade pandas>=0.25.0

升级后直接使用你原来的代码即可正常运行:

compression_options = {"method": "zip", "archive_name": f'report.csv'}
df.to_csv(f'../file location/report.csv.zip', compression=compression_options)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:01:55