本章介绍 pandas 对统计软件格式(Stata、SAS、SPSS)、Google BigQuery 和 Markdown 表格的支持。


1. Stata(.dta)

Stata 是经济学、社会科学研究常用统计软件。pandas 可读写 .dta 文件,并保留变量标签、值标签等元数据。

read_stata()

pd.read_stata(
    filepath_or_buffer, convert_dates=True, convert_categoricals=True,
    index_col=None, convert_missing=False, preserve_dtypes=True,
    columns=None, order_categoricals=True, chunksize=None,
    iterator=False, compression='infer', storage_options=None
)
参数说明
convert_dates是否将 Stata 日期转为 pandas 日期
convert_categoricals是否将 Stata 值标签转为 Categorical
index_col索引列
convert_missing将 Stata 缺失值符号转为 np.nan(默认使用原始表示)
preserve_dtypes保留 Stata 原始类型
columns读取列
chunksize分块读取

to_stata()

DataFrame.to_stata(
    path, convert_dates=None, write_index=True, byteorder=None,
    time_stamp=None, data_label=None, variable_labels=None,
    version=114, convert_strl=None, compression='infer',
    storage_options=None, value_labels=None
)
参数说明
convert_dates日期列转换映射
write_index是否写入索引
data_label数据集标签
variable_labels变量标签字典
versionStata 文件版本(114/117/118/119)
value_labels值标签字典
# 读取
df = pd.read_stata('data.dta')
 
# 写出
df.to_stata(
    'output.dta',
    data_label='我的数据集',
    variable_labels={'age': '年龄', 'income': '收入'}
)

2. SAS

SAS 是统计分析软件。pandas 通过 read_sas() 读取 SAS 数据集文件(.sas7bdat),仅支持读取。

read_sas()

pd.read_sas(
    filepath_or_buffer, format=None, index=None, encoding=None,
    chunksize=None, iterator=False, compression='infer',
    storage_options=None
)
参数说明
format'xport'(XPORT 格式,.xpt)
index索引列
encoding文件编码
chunksize分块读取
iterator返回迭代器
# 读取 .sas7bdat 文件
df = pd.read_sas('data.sas7bdat')
 
# 读取 XPORT 格式
df = pd.read_sas('data.xpt', format='xport')
 
# 分块读取
reader = pd.read_sas('large.sas7bdat', chunksize=10000)

说明

  • SAS 文件通常较大,建议指定 chunksize 或 iterator=True 分批处理。
  • sas7bdat 为新版格式,xport 为旧版交换格式。

3. SPSS(.sav)

SPSS 是社会科学研究中常用的统计分析软件。pandas 通过 read_spss() 读取 .sav 文件,仅支持读取,且不支持缺失值处理与值标签。

read_spss()

pd.read_spss(
    path, usecols=None, convert_categoricals=True,
    dtype_backend=_NoDefault.no_default
)
参数说明
pathSPSS 文件路径
usecols读取列
convert_categoricals是否将分类变量转为 Categorical
dtype_backend类型后端
# 读取
df = pd.read_spss('data.sav')

依赖提示

需要安装 pyreadstat:pip install pyreadstat


4. Google BigQuery(GBQ)

pandas 提供 read_gbq() 与 to_gbq() 实现与 Google BigQuery 的交互,通过 google-cloud-bigquery 客户端完成认证与查询。

read_gbq()

pd.read_gbq(
    query, project_id=None, index_col=None, col_order=None,
    reauth=False, auth_local_webserver=False, dialect=None,
    location=None, configuration=None, credentials=None,
    use_bqstorage_api=None, max_results=None, progress_bar_type=None
)
参数说明
querySQL 查询语句
project_idGoogle Cloud 项目 ID
dialect'standard' 或 'legacy'
credentialsGoogle 认证凭据
use_bqstorage_api是否使用 BigQuery Storage API(更快)
max_results最大返回行数
progress_bar_type进度条选项

to_gbq()

DataFrame.to_gbq(
    destination_table, project_id=None, chunksize=None,
    if_exists='fail', credentials=None, auth_local_webserver=False,
    table_schema=None, location=None, progress_bar_type=None
)
参数说明
destination_table目标表名(dataset.table)
if_exists'fail' / 'replace' / 'append'
chunksize分块写入大小
table_schema表结构定义(自动推断时可省略)
# 查询
df = pd.read_gbq('SELECT * FROM mydataset.mytable', project_id='my-project')
 
# 写出
df.to_gbq('mydataset.mytable', project_id='my-project', if_exists='replace')

依赖与环境

  • 需要安装:pip install pandas-gbq google-cloud-bigquery
  • 使用前需通过 Google Cloud 完成认证(导出服务账号密钥或使用 gcloud 登录)。

5. Markdown

pandas 支持读取 Markdown 表格,并可将 DataFrame 输出为 Markdown 格式的表格,非常适合在 GitHub、Obsidian 等场景中展示数据。

read_markdown()

pd.read_markdown(
    io, **kwargs
)

内部调用 read_html() 与 Tabulate 解析器,兼容 read_html() 的参数。

import pandas as pd
 
markdown_str = """
| 姓名 | 年龄 | 城市 |
|------|------|------|
| 张三 | 25   | 北京 |
| 李四 | 30   | 上海 |
"""
 
df = pd.read_markdown(markdown_str)
#    姓名  年龄 城市
# 0  张三  25  北京
# 1  李四  30  上海

to_markdown()

DataFrame.to_markdown(
    buf=None, mode='w', index=True, tablefmt='pipe',
    headers='keys', floatfmt=None, intfmt=None, showindex='default',
    colalign=None, **kwargs
)
参数说明
buf输出文件路径或文件对象,None 返回字符串
mode文件写入模式
index是否写出索引
tablefmt表格格式:'pipe'、'github'、'grid'、'plain'、'html' 等
headers表头内容
floatfmt浮点格式
intfmt整型格式
colalign列对齐方式
# 输出 Markdown 字符串
print(df.to_markdown())
 
# 指定 GitHub 风格
print(df.to_markdown(tablefmt='github'))
 
# 保存到文件
df.to_markdown('table.md', index=False)
 
# 不输出索引,保留两位小数
df.to_markdown(floatfmt='.2f', index=False)

Tabulate 扩展

to_markdown() 依赖 tabulate 库,安装后可使用更多表格格式:pip install tabulate。