核心内容

汇总各导出方法的 通用格式参数,并介绍 多 sheet 导出 与 压缩 两大高级功能。

一、格式参数

通用参数(跨格式)

参数适用方法说明
index几乎所有 to_*是否写入行索引
headerto_csv / to_html / to_excel / to_clipboard是否写入列名
columnsto_csv / to_html / to_excel / to_string选择导出列
na_repto_csv / to_html / to_excel / to_string / to_xml缺失值表示
float_formatto_csv / to_html / to_excel / to_string / to_latex浮点格式
encodingto_csv / to_html / to_json / to_xml / to_excel编码方式
compressionto_csv / to_json / to_pickle / to_parquet / to_hdf压缩方式
storage_optionsto_csv / to_parquet / to_json 等对象存储配置(S3 / GCS)

各格式特有参数速查

方法关键特有参数
to_csvsep、quoting、quotechar、line_terminator、date_format、chunksize、mode
to_jsonorient、date_format、force_ascii、date_unit、indent、lines
to_htmlformatters、col_space、justify、border、classes、render_links
to_latexcolumn_format、caption、label、hrules、longtable
to_markdowntablefmt、floatfmt、intfmt、stralign
to_xmlroot_name、row_name、attr_cols、elem_cols、namespaces、pretty_print
to_excelsheet_name、startrow、startcol、merge_cells、freeze_panes、inf_rep
to_sqlschema、if_exists、chunksize、dtype
to_parquetengine、compression、partition_cols、coerce_timestamps
to_hdfkey、mode、format、append、complevel、complib、data_columns
to_pickleprotocol(通过 pickle 传入)、compression
to_dictorient、into
to_recordsindex、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 获得最大压缩比

相关笔记