1.4 配置与选项

本节大纲

  • pd.get_option()
  • pd.set_option()
  • pd.reset_option()
  • pd.describe_option()
  • pd.option_context()
  • 选项分类
    • display
    • mode
    • compute
    • plotting
    • future

1. pd.get_option()

获取指定选项的当前值。

详细说明

  • 签名:pd.get_option(pat)
  • 参数:pat 为选项名(字符串),支持正则表达式匹配多个选项。
  • 示例:
    pd.get_option('display.max_rows')   # 返回 60
    pd.get_option('display.max_columns') # 返回 20 或 0(表示全部)
  • 批量获取:使用正则表达式,如 pd.get_option('display.*') 会返回所有 display 相关选项的字典。

2. pd.set_option()

设置选项的值。

详细说明

  • 签名:pd.set_option(pat, value)
  • 参数:
    • pat:选项名,支持正则。
    • value:新值。
  • 示例:
    pd.set_option('display.max_rows', 100)
    pd.set_option('display.max_columns', None)  # None 表示不限制
  • 同时设置多个:传入字典 pd.set_option({'display.max_rows':100, 'display.width':200})。
  • 注意:某些选项设置后立即生效,且在整个 Python 会话中保持。

3. pd.reset_option()

将选项重置为默认值。

详细说明

  • 签名:pd.reset_option(pat)
  • 参数:pat 为选项名或正则表达式。
  • 示例:
    pd.reset_option('display.max_rows')     # 重置单个
    pd.reset_option('^display')             # 重置所有以 display 开头的选项
    pd.reset_option('all')                  # 重置所有选项
  • 注意:'all' 是特殊字符串,重置全部选项。

4. pd.describe_option()

显示选项的详细描述,包括默认值、当前值和可选值。

详细说明

  • 签名:pd.describe_option(pat, _print_desc=False)
  • 示例:
    pd.describe_option('display.max_rows')
    输出类似:
    display.max_rows : int
        If max_rows is exceeded, switch to truncate view.
        [default: 60] [currently: 100]
    
  • 用途:了解选项的作用和取值范围,便于正确设置。
  • 正则匹配:pd.describe_option('display') 描述所有 display 选项。

5. pd.option_context()

临时修改选项的上下文管理器,退出时自动恢复。

详细说明

  • 签名:pd.option_context(*args)
  • 用法:
    with pd.option_context('display.max_rows', 10, 'display.width', 200):
        print(df)
    # 离开 with 块后,选项恢复原值
  • 优点:避免手动保存和恢复选项,代码更整洁。
  • 支持多个选项:参数形式为 key, value 交替或字典。
  • 示例:
    with pd.option_context('display.max_rows', 5):
        display(df)

6. 选项分类

6.1 display 类

控制数据在终端或 notebook 中的显示方式。

选项默认值说明
display.max_rows60显示的最大行数,超过则截断。设为 None 显示全部。
display.max_columns20显示的最大列数,超过则用省略号。None 显示全部。
display.width80输出总宽度(字符数)。
display.max_colwidth50每列中字符串的最大宽度,超过截断。None 不限。
display.precision6浮点数的显示精度(小数位数)。
display.float_formatNone格式化浮点数的函数,如 lambda x: f'{x:.2f}'。
display.colheader_justify’right’列标题对齐方式:‘left’/‘right’/‘center’。
display.expand_frame_reprTrue是否在宽 DataFrame 时分块显示。
display.show_dimensions’truncate’是否显示 DataFrame 的维度信息(‘truncate’/‘always’/‘None’)。
display.unicode.east_asian_widthFalse处理东亚字符宽度。
display.encoding’UTF-8’输出编码。

6.2 mode 类

控制 pandas 的行为模式。

选项默认值说明
mode.chained_assignment’warn’链式赋值处理方式:‘warn’(警告)、‘raise’(报错)、None(静默)。在 CoW 下建议 ‘raise’。
mode.data_manager’block’内部数据管理器类型:‘block’ 或 ‘array’。一般无需修改。
mode.use_inf_as_naFalse是否将 inf 视为缺失值(一般不推荐)。
mode.copy_on_writeTrue启用 Copy-on-Write,建议保持 True。
mode.string_storage’python’字符串存储后端:‘python’ 或 ‘pyarrow’。

6.3 compute 类

控制计算相关的优化选项。

选项默认值说明
compute.use_bottleneckTrue是否使用 bottleneck 库加速 sum、mean 等统计函数。
compute.use_numbaFalse是否使用 numba JIT 加速某些操作(需安装 numba)。

6.4 plotting 类

控制绘图相关设置。

选项默认值说明
plotting.backend’matplotlib’绘图后端名称,如 ‘plotly’、‘hvplot’ 等。
plotting.matplotlib.register_convertersTrue是否注册 pandas 的日期转换器到 matplotlib。

6.5 future 类

控制未来版本中即将成为默认行为的选项。

选项默认值说明
future.infer_stringFalse是否自动将字符串推断为 string dtype(pandas 3.0 中将默认启用)。
future.copy_on_writeFalse是否默认启用 Copy-on-Write(2.3 中已通过 mode.copy_on_write 默认启用,此选项可能用于提前体验)。
future.no_silent_downcastingFalse是否禁止静默类型降级(如 int64 到 int32),设为 True 会抛出错误。

配置建议

  • 在项目开始时设置全局选项,保持一致性。
  • 对于临时调整,使用 pd.option_context() 更安全。
  • 升级 pandas 时关注 future 选项,提前适应新行为。

注意

某些选项(如 mode.copy_on_write)一旦启用会改变底层行为,需确保代码兼容。建议在 pandas 2.3 中始终开启 Copy-on-Write。