to_csv()、to_excel() 等一系列方法,可以方便地将 DataFrame 写入多种常见格式,便于后续分享、报表生成或导入其他系统。
to_csv() 是最常用的导出方法,支持灵活的参数配置。
import pandas as pd
df = pd.DataFrame({
'姓名': ['张三', '李四', '王五'],
'年龄': [28, 35, 42],
'工资': [8000, 12000, 15000]
})
# 基本写入
df.to_csv('output.csv', index=False) # 不保存行索引
# 常用参数示例
df.to_csv('output.csv',
sep=';', # 使用分号分隔(避免逗号冲突)
na_rep='NULL', # 缺失值替换为 NULL
encoding='utf-8', # 编码
columns=['姓名', '工资'], # 只保存指定列
header=True, # 是否保存列名
index=True, # 保存行索引(默认 True)
index_label='id' # 索引列的名称
)
sep分隔符,默认为逗号 ,。可使用 '\t' 制表符等。
na_rep缺失值的表示形式,默认为空字符串。
encoding文件编码,如 'utf-8'、'gbk'。
columns指定要写入的列,可减少输出文件大小。
header是否写入列名,默认为 True。若为 False 则不输出列名。
index是否写入行索引,默认为 True。通常设为 False 避免多余列。
需要安装 openpyxl(.xlsx)或 xlsxwriter。通过 to_excel() 和 ExcelWriter 可实现单表或多工作表写入。
# 写入单个工作表
df.to_excel('output.xlsx', sheet_name='员工信息', index=False)
# 使用 ExcelWriter 写入多个工作表
with pd.ExcelWriter('output.xlsx', engine='openpyxl') as writer:
df1.to_excel(writer, sheet_name='员工信息', index=False)
df2.to_excel(writer, sheet_name='部门信息', index=False)
# 参数示例
df.to_excel('output.xlsx',
sheet_name='Sheet1',
index=False,
startrow=2, # 从第3行开始写入(留出标题行)
startcol=1, # 从第2列开始
columns=['姓名', '年龄'], # 只写入指定列
na_rep='NULL', # 缺失值表示
inf_rep='INF' # 无穷大表示
)
如果需要格式控制(如设置列宽、颜色等),建议使用 xlsxwriter 引擎:
with pd.ExcelWriter('styled.xlsx', engine='xlsxwriter') as writer:
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.set_column('A:A', 20) # 设置A列宽度20
to_json() 可导出为 JSON 格式,常用参数 orient 控制结构。
# 默认格式(按列索引)
df.to_json('output.json')
# 常用 orient 选项
df.to_json('output.json', orient='records') # 列表形式:[{col:val}, ...]
df.to_json('output.json', orient='index') # 以索引为键
df.to_json('output.json', orient='columns') # 以列为键(默认)
df.to_json('output.json', orient='split') # 分成 index, columns, data 三部分
# 压缩与行分隔 JSON(适用于大数据流)
df.to_json('output.json', orient='records', lines=True) # 每行一个JSON对象
需要 SQLAlchemy 和相应数据库驱动。to_sql() 可将 DataFrame 直接写入数据库表。
from sqlalchemy import create_engine
engine = create_engine('sqlite:///mydatabase.db')
df.to_sql('employees',
con=engine,
if_exists='replace', # 'fail'(表存在时报错)、'replace'(替换)、'append'(追加)
index=False, # 不写入行索引
dtype={ # 指定列的数据类型(SQLAlchemy类型)
'年龄': sqlalchemy.types.INTEGER(),
'工资': sqlalchemy.types.Float(precision=10, scale=2)
})
df.to_hdf('data.h5', key='df', mode='w') 适合存储大型数组数据df.to_parquet('data.parquet') 列式存储,高效压缩df.to_feather('data.feather') 跨语言快速读写df.to_pickle('data.pkl') Python对象序列化df.to_markdown('table.md') 生成表格文档df.to_html('table.html') 生成网页表格import pandas as pd
import numpy as np
# 创建示例数据
df = pd.DataFrame({
'product': ['A', 'B', 'C', 'D'],
'price': [100, 250, 175, None],
'quantity': [5, 10, 8, 3],
'date': pd.date_range('2024-01-01', periods=4)
})
# 导出 CSV(不含索引,缺失值填 'NA')
df.to_csv('products.csv', index=False, na_rep='NA')
# 导出 Excel 并设置日期格式
with pd.ExcelWriter('products.xlsx', engine='xlsxwriter') as writer:
df.to_excel(writer, sheet_name='Products', index=False)
workbook = writer.book
worksheet = writer.sheets['Products']
# 设置日期列格式
date_format = workbook.add_format({'num_format': 'yyyy-mm-dd'})
worksheet.set_column('D:D', 12, date_format)
# 导出 JSON(records 格式,行分隔)
df.to_json('products.json', orient='records', lines=True)
# 导出 SQLite
from sqlalchemy import create_engine
engine = create_engine('sqlite:///products.db')
df.to_sql('products', con=engine, if_exists='replace', index=False)
encoding,如中文用 encoding='gbk' 或 'utf-8-sig'(带BOM的UTF-8)。
xlsxwriter 优化;大文件可用 CSV 替代。
df['date'] = df['date'].dt.tz_convert('UTC').dt.tz_localize(None) 去除时区。
dtype 参数指定 SQL 类型,或预先转换 DataFrame 列类型。
index=False),除非索引本身是有意义的数据列。df.info() 检查数据类型,避免意外转换。