python - 将 pandas DataFrame 写入 gzip csv,存档中没有时间戳
问题描述
将 pandas DataFrame 写入 gzip 压缩的 CSV 会将时间戳添加到存档中:
import pandas as pd
df = pd.DataFrame({'a': [1]})
df.to_csv('df.csv.gz', compression='gzip')
# Timestamp is the large number per https://unix.stackexchange.com/a/79546/88807.
!<df.csv.gz dd bs=4 skip=1 count=1 | od -t d4
# 1+0 records in
# 1+0 records out
# 4 bytes copied, 5.6233e-05 s, 71.1 kB/s
# 0000000 1546978755
# 0000004df.csv
我想写它没有时间戳,这样同一个 DataFrame 的两个后续导出是相同的:
df.to_csv('df2.csv.gz', compression='gzip')
import filecmp
filecmp.cmp('df.csv.gz', 'df2.csv.gz')
# False
解决方案
在查看了用于CSV 编写的 Pandas 代码后,我能建议的最好方法是gzip
直接使用该模块。这样您就可以直接设置似乎是您想要的mtime
属性:
import pandas as pd
from gzip import GzipFile
from io import TextIOWrapper
def to_gzip_csv_no_timestamp(df, f, *kwargs):
# Write pandas DataFrame to a .csv.gz file, without a timestamp in the archive
# header, using GzipFile and TextIOWrapper.
#
# Args:
# df: pandas DataFrame.
# f: Filename string ending in .csv (not .csv.gz).
# *kwargs: Other arguments passed to to_csv().
#
# Returns:
# Nothing.
with TextIOWrapper(GzipFile(f, 'w', mtime=0), encoding='utf-8') as fd:
df.to_csv(fd, *kwargs)
to_gzip_csv_no_timestamp(df, 'df.csv.gz')
to_gzip_csv_no_timestamp(df, 'df2.csv.gz')
filecmp.cmp('df.csv.gz', 'df2.csv.gz')
# True
subprocess
对于这个小数据集,这优于下面的两步方法:
%timeit to_gzip_csv_no_timestamp(df, 'df.csv')
693 us +- 14.6 us per loop (mean +- std. dev. of 7 runs, 1000 loops each)
%timeit to_gzip_csv_no_timestamp_subprocess(df, 'df.csv')
10.2 ms +- 167 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
我正在使用 aTextIOWrapper()
来处理Pandas将字符串转换为字节的操作,但如果您知道不会保存太多数据,也可以这样做:
with GzipFile('df.csv.gz', 'w', mtime=0) as fd:
fd.write(df.to_csv().encode('utf-8'))
请注意,它gzip -lv df.csv.gz
仍然显示“当前时间”,但它只是从 inode 的 mtime 中提取出来的。dumping withhexdump -C
显示值保存在文件中,更改文件 mtime (with touch -mt 0711171533 df.csv.gz
) 会导致gzip
显示不同的值
另请注意,原始“文件名”也是 gzip 压缩文件的一部分,因此您需要写入相同的名称(或覆盖此名称)以使其具有确定性。
推荐阅读
- emacs - 返回 cdr 的点完成函数
- python - 使用线程池下载多个 url
- vba - 单击功能区按钮时禁用多个按钮
- python - 从 html 输入标签中的 django 日期时间字段渲染时间时出现问题
- c# - 在没有内存泄漏的情况下在 NPOCO C# 模型中同时维护 FK 属性和连接对象?
- python - 如何将 STL 文件转换为大小为 256x256x256 的 numpy 数组?
- python - 通过 Django 中的 Fixtures 使用 YAML 文件填充数据库中的数据
- java - 没有调用paintComponent()
- python - 扩展 Django AbstractUser 时的附加身份验证表
- css - iOS Safari 全屏更改 window.innerWidth