使用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
相关产品推荐
相关产品推荐

