核心内容
汇总各导出方法的 通用格式参数,并介绍 多 sheet 导出 与 压缩 两大高级功能。
一、格式参数
通用参数(跨格式)
| 参数 | 适用方法 | 说明 |
|---|---|---|
index | 几乎所有 to_* | 是否写入行索引 |
header | to_csv / to_html / to_excel / to_clipboard | 是否写入列名 |
columns | to_csv / to_html / to_excel / to_string | 选择导出列 |
na_rep | to_csv / to_html / to_excel / to_string / to_xml | 缺失值表示 |
float_format | to_csv / to_html / to_excel / to_string / to_latex | 浮点格式 |
encoding | to_csv / to_html / to_json / to_xml / to_excel | 编码方式 |
compression | to_csv / to_json / to_pickle / to_parquet / to_hdf | 压缩方式 |
storage_options | to_csv / to_parquet / to_json 等 | 对象存储配置(S3 / GCS) |
各格式特有参数速查
| 方法 | 关键特有参数 |
|---|---|
to_csv | sep、quoting、quotechar、line_terminator、date_format、chunksize、mode |
to_json | orient、date_format、force_ascii、date_unit、indent、lines |
to_html | formatters、col_space、justify、border、classes、render_links |
to_latex | column_format、caption、label、hrules、longtable |
to_markdown | tablefmt、floatfmt、intfmt、stralign |
to_xml | root_name、row_name、attr_cols、elem_cols、namespaces、pretty_print |
to_excel | sheet_name、startrow、startcol、merge_cells、freeze_panes、inf_rep |
to_sql | schema、if_exists、chunksize、dtype |
to_parquet | engine、compression、partition_cols、coerce_timestamps |
to_hdf | key、mode、format、append、complevel、complib、data_columns |
to_pickle | protocol(通过 pickle 传入)、compression |
to_dict | orient、into |
to_records | index、column_dtypes、index_dtypes |
二、导出多 sheet
ExcelWriter 多 sheet
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2]})
df2 = pd.DataFrame({'B': [3, 4]})
# 方案 1:with 块(推荐)
with pd.ExcelWriter('multi_sheet.xlsx') as writer:
df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet2', index=False)
# 同一 sheet 不同起始位置
df1.to_excel(writer, sheet_name='Sheet3', startrow=0)
df1.to_excel(writer, sheet_name='Sheet3', startrow=5)
# 方案 2:先创建 writer
writer = pd.ExcelWriter('multi_sheet.xlsx', engine='openpyxl')
df1.to_excel(writer, sheet_name='Data1')
df2.to_excel(writer, sheet_name='Data2')
writer.save()
writer.close()HDF / Parquet 多数据集
# HDF5 多 key
with pd.HDFStore('multi.h5') as store:
store.put('key1', df1)
store.put('key2', df2)
# Parquet 分区目录(按列值分区)
df.to_parquet('partitioned/', partition_cols=['region', 'year'])
# 多表 Parquet(手动)
# 每个表一个文件
df1.to_parquet('table1.parquet')
df2.to_parquet('table2.parquet')SQL 多表
# 同一数据库写入多张表
df1.to_sql('table1', engine, if_exists='replace')
df2.to_sql('table2', engine, if_exists='replace')三、压缩
compression 参数支持的值
| 值 | 说明 | 文件后缀 |
|---|---|---|
None / 'infer' | 根据文件后缀自动推断 | 任意 |
'gzip' | gzip 压缩,压缩比高 | .gz |
'bz2' | bzip2,压缩比最高但慢 | .bz2 |
'zip' | ZIP 格式 | .zip |
'xz' | xz(LZMA),高压缩比 | .xz |
'zstd' | Zstandard,速度与比平衡 | .zst |
{'method': ..., 'compresslevel': ...} | 字典形式,指定压缩级别 | — |
# CSV 压缩
df.to_csv('data.csv.gz', compression='gzip')
df.to_csv('data.csv.gz', compression={'method': 'gzip', 'compresslevel': 9})
# JSON 压缩
df.to_json('data.json.gz', compression='gzip', orient='records')
# Parquet 压缩(snappy / gzip / zstd / lz4)
df.to_parquet('data.parquet', compression='zstd')
# HDF5 压缩
df.to_hdf('data.h5', key='df', format='table', complevel=9, complib='zlib')压缩对比
| 算法 | 压缩比 | 速度 | 适用场景 |
|---|---|---|---|
snappy | 低 | 极快 | Parquet 默认,大数据分析 |
gzip | 中 | 中 | 通用文本压缩 |
bz2 | 高 | 慢 | 磁盘空间极端紧张 |
xz | 最高 | 最慢 | 存档场景 |
zstd | 高 | 快 | 推荐通用(平衡) |
lz4 | 低 | 最快 | 需要极速读写 |
读取压缩文件
# 后缀自动识别
pd.read_csv('data.csv.gz')
# 显式指定
pd.read_csv('data.csv', compression='gzip')
# 多文件 zip
df = pd.read_csv('all.zip', compression='zip')实践建议
- 文本型大文件(CSV / JSON)优先
gzip或zstd- 列式格式(Parquet)直接用其原生压缩参数
- 归档需求使用
xz获得最大压缩比
相关笔记
- 23.6 文本格式导出 - 各类文本格式的详细参数
- 23.2 二进制格式导出 - Parquet / HDF5 压缩配置
- Pandas-四-数据输入输出 - 对应的读取函数