Appearance
写入文件
Pandas 支持将数据导出为多种格式,方便数据共享和存储。
写入CSV
python
import pandas as pd
df = pd.DataFrame({
'姓名': ['张三', '李四', '王五'],
'年龄': [25, 30, 35],
'城市': ['北京', '上海', '广州']
})
# 基础写入
df.to_csv('output.csv', index=False)
# 指定编码
df.to_csv('output.csv', encoding='utf-8-sig') # 带BOM,Excel兼容
df.to_csv('output.csv', encoding='gbk')
# 指定分隔符
df.to_csv('output.tsv', sep='\t', index=False)
# 只写入特定列
df.to_csv('output.csv', columns=['姓名', '年龄'], index=False)
# 追加写入
df.to_csv('output.csv', mode='a', header=False, index=False)写入Excel
python
# 基础写入
df.to_excel('output.xlsx', index=False)
# 写入指定工作表
df.to_excel('output.xlsx', sheet_name='员工信息', index=False)
# 写入多个工作表
with pd.ExcelWriter('output.xlsx') as writer:
df.to_excel(writer, sheet_name='Sheet1', index=False)
df.to_excel(writer, sheet_name='Sheet2', index=False)
# 不写入索引
df.to_excel('output.xlsx', index=False)
# 冻结首行
df.to_excel('output.xlsx', index=False, freeze_panes=(1, 0))写入JSON
python
# 基础写入
df.to_json('output.json')
# 按行写入
df.to_json('output.json', orient='records')
# 格式化输出
df.to_json('output.json', orient='records', force_ascii=False, indent=2)
# 写入JSON字符串
json_str = df.to_json(orient='records', force_ascii=False)
print(json_str)写入其他格式
python
# 写入HTML
df.to_html('output.html', index=False)
# 写入Markdown
df.to_markdown('output.md', index=False)
# 写入LaTeX
df.to_latex('output.tex', index=False)
# 写入剪贴板
df.to_clipboard(index=False)写入数据库
python
from sqlalchemy import create_engine
# 创建连接
engine = create_engine('sqlite:///database.db')
# 写入数据
df.to_sql('employees', engine, index=False, if_exists='replace')
# 追加数据
df.to_sql('employees', engine, index=False, if_exists='append')
# 写入MySQL
engine = create_engine('mysql+pymysql://user:password@localhost/dbname')
df.to_sql('employees', engine, index=False, if_exists='replace')大数据写入
python
# 分块写入大文件
chunk_size = 1000
chunks = pd.read_csv('large_input.csv', chunksize=chunk_size)
for i, chunk in enumerate(chunks):
mode = 'w' if i == 0 else 'a'
header = i == 0
chunk.to_csv('large_output.csv', mode=mode, header=header, index=False)压缩写入
python
# 写入压缩文件
df.to_csv('output.csv.gz', compression='gzip', index=False)
df.to_csv('output.csv.zip', compression='zip', index=False)
df.to_csv('output.csv.bz2', compression='bz2', index=False)
# 读取压缩文件
df = pd.read_csv('output.csv.gz', compression='gzip')格式选项
python
# 设置浮点数精度
df.to_csv('output.csv', float_format='%.2f', index=False)
# 处理缺失值
df.to_csv('output.csv', na_rep='NULL', index=False)
# 设置日期格式
df.to_csv('output.csv', date_format='%Y-%m-%d', index=False)
# 引用选项
df.to_csv('output.csv', quoting=1, index=False) # 全部引用
df.to_csv('output.csv', quotechar="'", index=False) # 自定义引号字符数据导出是数据分析的最后一步,选择合适的格式可以方便数据的共享和后续使用。