核心内容

将 DataFrame 导出为 剪贴板文本(to_clipboard) 与 字符串(to_string)。

一、to_clipboard() — 导出剪贴板

将 DataFrame 以 TSV(制表符分隔)复制到系统剪贴板,可直接粘贴到 Excel / 表格软件。

import pandas as pd
 
df = pd.DataFrame({
    'id': [1, 2, 3],
    'name': ['Alice', 'Bob', 'Charlie'],
    'score': [95.5, 88.0, 76.25]
})
 
# 复制到剪贴板
df.to_clipboard()
 
# 参数
df.to_clipboard(
    excel=True,               # True=TSV(Excel 可识别),False=CSV
    sep=None,                 # 自定义分隔符(不指定时由 excel 决定)
    index=True,               # 是否包含索引
    header=True,              # 是否包含列名
    encoding=None             # 编码
)
 
# 在 Excel 中直接 Ctrl+V 粘贴
参数说明
excelTrue 时生成制表符分隔文本,可直接粘贴 Excel
sep自定义分隔符
index / header是否包含索引 / 列头

二、to_string() — 导出字符串

将 DataFrame 渲染为格式化字符串(与控制台输出类似),常用于日志、报告生成。

# 基础用法
text = df.to_string()
print(text)
 
# 常用参数
df.to_string(
    buf=None,                  # 文件对象 / StringIO
    columns=['name', 'score'], # 选择列
    col_space=12,              # 列宽或列宽列表
    header=True,               # 是否显示列名
    index=True,                # 是否显示索引
    na_rep='NaN',              # 缺失值表示
    formatters={               # 按列格式化
        'score': lambda x: f'{x:.1f}'
    },
    float_format='%.2f',       # 浮点格式化
    sparsify=True,             # 多级索引合并
    index_names=True,          # 显示索引名
    justify='right',           # 对齐方式
    max_rows=50,               # 最大显示行数
    max_cols=20,               # 最大显示列数
    show_dimensions=True,      # 显示维度
    decimal='.',               # 小数点
    line_width=80              # 换行宽度
)

场景示例

# 写入日志文件
with open('report.log', 'a') as f:
    f.write(df.to_string(index=False))
    f.write('\n')
 
# 邮件 / 消息中发送
report = df.head(10).to_string(index=False, float_format='%.2f')
message = f'每日报表:\n```\n{report}\n```'
 
# 配合 StringIO
from io import StringIO
buffer = StringIO()
df.to_string(buffer)
content = buffer.getvalue()

to_string() vs str(df)

  • str(df) 等价于 df.to_string() 的简化版
  • to_string() 提供更多精细控制(列宽、格式化、截断)

控制截断

# 完全显示(大数据时慎用)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
print(df.to_string(max_rows=None, max_cols=None))

相关笔记