拓冰建站拓冰建站
首页 / 资讯中心 / 正文

pandas 选项系统(Options and settings)完全指南:从配置 API 到源码级原理

pandas 选项系统Options and settings完全指南从配置 API 到源码级原理【免费下载链接】pandasFlexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more项目地址: https://gitcode.com/gh_mirrors/pa/pandas导读本文围绕 pandas 的全局选项系统Options API展开系统讲解display.max_rows这类点分式选项的获取、设置、重置与临时作用域管理覆盖get_option/set_option/reset_option/describe_option/option_context五大核心函数并结合当前仓库源码pandas/_config/config.py 与 pandas/core/config_init.py剖析其底层注册、校验、回调与默认值机制。读完本文你将掌握 pandas 显示格式、Unicode 对齐、表格模式、计算引擎等全局行为的精细调优方法并能理解在 pandas/tests/config/test_config.py 中如何对这套系统进行测试验证。一、Overviewpandas 的全局选项 APIpandas 提供了一套全局选项 APIOptions API用于配置和定制与DataFrame展示、数据处理行为等相关的全局设置。这套机制的价值在于无需修改业务代码即可在不同运行环境终端、Jupyter Notebook、批量脚本之间切换输出风格和行为模式。选项拥有完整、大小写不敏感的点分式dotted-style名称例如display.max_rows。你既可以使用pd.get_option/pd.set_option这类函数式接口也可以直接把它当作顶层options对象的属性来读写import pandas as pd pd.options.display.max_rows pd.options.display.max_rows 999 pd.options.display.max_rows这种属性式访问由源码中的DictWrapper类实现pandas/_config/config.py它把内部的嵌套字典_global_config包装成可通过属性访问的对象__getattr__遇到字典子树时继续返回DictWrapper遇到叶子节点时则转调get_option(prefix)__setattr__只允许设置已存在的叶子选项否则抛出OptionError(You can only set the value of existing options)。API 由 5 个核心函数组成它们都直接暴露在pandas命名空间下见 pandas/init.py函数作用pandas.get_option(pat)/pandas.set_option(pat, value)获取 / 设置单个选项的值pandas.reset_option(pat)将一个或多个选项重置为默认值pandas.describe_option(pat)打印一个或多个选项的描述pandas.option_context(*args)在with代码块内临时设置选项退出后自动还原开发者若想深入了解整套选项的注册细节可以直接阅读仓库中的 pandas/core/config_init.py所有内置选项都在该模块的导入阶段完成注册。支持正则re.search 风格的模式匹配上述所有函数都接受一个正则模式参数re.search风格用于匹配唯一无歧义的子串pd.get_option(display.chop_threshold) pd.set_option(display.chop_threshold, 2) pd.get_option(display.chop_threshold) pd.set_option(chop, 4) # 缩写同样有效 pd.get_option(display.chop_threshold)但下面的写法会失败因为max会同时命中多个选项名如display.max_colwidth、display.max_rows、display.max_columnspd.get_option(max) # OptionError: Pattern matched multiple keys从源码看模式匹配逻辑位于_select_optionspandas/_config/config.py先做精确键短路匹配否则对所有已注册键执行re.search(pat, k, re.I)忽略大小写。命中 0 个键抛出OptionError(fNo such keys(s): {pat!r})命中多个键抛出OptionError(Pattern matched multiple keys)。警告使用这种简写形式可能导致代码在未来版本中失效——一旦 pandas 新增了名字相似的新选项简写匹配就可能命中多个键而抛错。生产环境建议始终使用完整的点分选项名。二、Available options枚举全部可用选项调用describe_option()无参数可以打印出全部已注册选项及其描述pd.describe_option()该函数内部通过_select_options()收集所有键再对每个键调用_build_option_description拼装出键名 文档 [default: ...] [currently: ...]格式的描述文本pandas/_config/config.py。对于已经标记废弃的选项描述中还会附加(Deprecated, use ... instead.)提示。也可以传入正则来精确查看某一类选项pd.describe_option(display.max_rows) pd.describe_option(^display) # 查看所有 display.* 选项三、Getting and setting options选项的读写与重置3.1 get_option / set_option如上文所述get_option与set_option直接可从 pandas 命名空间调用。修改选项的通用姿势是set_option(option regex, new_value)pd.get_option(mode.sim_interactive) pd.set_option(mode.sim_interactive, True) pd.get_option(mode.sim_interactive)注意mode.sim_interactive选项主要用于调试/测试目的模拟交互模式。其注册代码见 pandas/core/config_init.py默认值为False。set_option还支持两种便捷输入形式源码 docstring 中均有示例# 1) 成对传参pattern, value, pattern, value, ... pd.set_option(display.max_columns, 4, display.precision, 1) # 2) 传入单个字典 pd.set_option({display.max_columns: 4, display.precision: 1})实现上字典输入会在_set_option_impl入口被展开为扁平元组若参数个数为奇数则抛出ValueErrorpandas/_config/config.py。3.2 reset_option恢复默认值使用reset_option可以把选项恢复到默认值pd.get_option(display.max_rows) pd.set_option(display.max_rows, 999) pd.get_option(display.max_rows) pd.reset_option(display.max_rows) pd.get_option(display.max_rows)也可以一次性重置多个选项使用正则pd.reset_option(^display) # 重置所有 display.* 选项reset_option(all)则是保留关键字用于重置全部选项。源码对多键重置有一个保护性约束当匹配到多个键且模式长度小于 4且不是all时会抛出ValueError提示用户至少给出 4 个字符或使用all关键字pandas/_config/config.py。3.3 option_context临时作用域option_context上下文管理器允许你在with块内以临时选项值执行代码退出with块时选项值自动恢复with pd.option_context(display.max_rows, 10, display.max_columns, 5): print(pd.get_option(display.max_rows)) # 10 print(pd.get_option(display.max_columns)) # 5 print(pd.get_option(display.max_rows)) # 恢复原值 print(pd.get_option(display.max_columns)) # 恢复原值它也支持字典形式with option_context({display.max_rows: 10, display.max_columns: 5}):。从源码看pandas/_config/config.pyoption_context的实现要点是进入块前先用warnFalse静默读取所有旧值存入undo元组然后依次_set_option_impl应用新值finally块中再静默还原旧值。因此即使with块内抛出异常选项也会被正确还原——这也是它比手动 set/reset 更安全的原因。四、Setting startup options在 Python/IPython 启动时自动配置在 Python/IPython 环境的启动脚本startup scripts中导入 pandas 并设置选项可以显著提升日常交互效率——你不需要每次启动后手动敲一堆set_option。做法在目标 profile 的 startup 目录下创建一个.py或.ipy脚本。默认 IPython profile 的 startup 目录形如$IPYTHONDIR/profile_default/startup一个典型的 pandas 启动脚本示例如下import pandas as pd pd.set_option(display.max_rows, 999) pd.set_option(display.precision, 5)这样每次进入 IPython 会话display.max_rows自动放宽到 999避免大数据集被截断、数值输出精度自动设为 5 位小数。更多关于 IPython 启动文件机制的说明可查阅 IPython 官方文档的 Startup Files 章节。五、Frequently used options高频展示选项详解以下逐一演示最常用的显示类选项所有示例均可直接复制运行。5.1 display.max_rows / display.max_columns / display.min_rowsdisplay.max_rows与display.max_columns控制 DataFrame 被美化打印pretty-print时的最大行数/列数超出的部分被省略号...替代import numpy as np df pd.DataFrame(np.random.randn(7, 2)) pd.set_option(display.max_rows, 7) df # 7 行全部显示 pd.set_option(display.max_rows, 5) df # 超出 5 行中间被省略 pd.reset_option(display.max_rows)当行数超过display.max_rows后截断视图实际展示的行数由display.min_rows决定pd.set_option(display.max_rows, 8) pd.set_option(display.min_rows, 4) # 行数未超过 max_rows - 全部行都显示 df pd.DataFrame(np.random.randn(7, 2)) df # 行数超过 max_rows - 只显示 min_rows4行 df pd.DataFrame(np.random.randn(9, 2)) df pd.reset_option(display.max_rows) pd.reset_option(display.min_rows)从 pandas/core/config_init.py 可看到这些选项的注册默认值display.precision默认6display.max_rows默认60display.min_rows默认10display.max_categories默认8display.max_colwidth默认50。display.max_columns的默认值比较特殊pandas/core/config_init.py如果 pandas 检测到运行在终端中默认0表示自动探测最优列数否则如 Notebook、qtconsole、IDLE默认20。display.max_rows设为0时在终端 large_reprtruncate的组合下同样会触发高度自动探测设为None表示无限制但要小心打印超大结果可能让渲染环境浏览器等崩溃。5.2 display.expand_frame_reprdisplay.expand_frame_repr允许宽 DataFrame 的表示形式跨页展开、按列换行包裹显示df pd.DataFrame(np.random.randn(5, 10)) pd.set_option(expand_frame_repr, True) df pd.set_option(expand_frame_repr, False) df pd.reset_option(expand_frame_repr)注意expand_frame_repr本身可被简写为不带display.前缀因为它无歧义。其 doc 说明开启时即便列数超过max_columns只要总宽度超出display.width输出会跨多行分页包裹max_columns依然生效。5.3 display.large_reprdisplay.large_repr决定超过max_columns/max_rows的 DataFrame 展示为截断表格还是信息摘要df pd.DataFrame(np.random.randn(10, 10)) pd.set_option(display.max_rows, 5) pd.set_option(large_repr, truncate) # 截断表格视图 df pd.set_option(large_repr, info) # 切换到 df.info() 式摘要 df pd.reset_option(large_repr) pd.reset_option(display.max_rows)该选项的合法取值仅为truncate与info验证器为is_one_of_factory([truncate, info])见 pandas/core/config_init.py默认truncate。5.4 display.max_colwidthdisplay.max_colwidth设置列的最大显示宽度字符数达到或超过该长度的单元格会被截断并插入省略号df pd.DataFrame( np.array( [ [foo, bar, bim, uncomfortably long string], [horse, cow, banana, apple], ] ) ) pd.set_option(max_colwidth, 40) df pd.set_option(max_colwidth, 6) df pd.reset_option(max_colwidth)默认值50类型为int非负或None无限制。5.5 display.max_info_columns / display.max_info_rowsdisplay.max_info_columns是DataFrame.info()打印逐列信息时的列数阈值df pd.DataFrame(np.random.randn(10, 10)) pd.set_option(max_info_columns, 11) df.info() pd.set_option(max_info_columns, 5) df.info() pd.reset_option(max_info_columns)display.max_info_rows则针对info()的 null 计数检查df.info()通常会为每列显示非空计数对超大 DataFrame 这可能会很慢。max_info_rows与max_info_cols把 null 检查限制在指定行/列范围内。info()的关键字参数show_countsTrue会覆盖这一限制df pd.DataFrame(np.random.choice([0, 1, np.nan], size(10, 10))) pd.set_option(max_info_rows, 11) df.info() pd.set_option(max_info_rows, 5) df.info() pd.reset_option(max_info_rows)默认max_info_rows为1690785、max_info_columns为100pandas/core/config_init.py。5.6 display.precisiondisplay.precision设置输出显示精度十进制小数位数df pd.DataFrame(np.random.randn(5, 5)) pd.set_option(display.precision, 7) df pd.set_option(display.precision, 4) df该选项通过is_nonnegative_int验证非负整数或 None其 doc 说明它与numpy.set_printoptions的precision类似既影响常规格式化也影响科学计数法。5.7 display.chop_thresholddisplay.chop_threshold设置显示时的归零阈值绝对值小于该阈值的浮点数在显示时呈现为0。注意它不改变数值的存储精度df pd.DataFrame(np.random.randn(6, 6)) pd.set_option(chop_threshold, 0) df pd.set_option(chop_threshold, 0.5) # 所有 |x| 0.5 的数显示为 0 df pd.reset_option(chop_threshold)默认值为None即不启用归零。5.8 display.colheader_justifydisplay.colheader_justify控制列标题的对齐方式合法取值为right与leftdf pd.DataFrame( np.array([np.random.randn(6), np.random.randint(1, 9, 6) * 0.1, np.zeros(6)]).T, columns[A, B, C], dtypefloat, ) pd.set_option(colheader_justify, right) df pd.set_option(colheader_justify, left) df pd.reset_option(colheader_justify)默认值为right验证器为is_text接受 str/bytes 实例。六、Number formatting数字格式化的精细控制pandas 允许你控制数字在控制台的显示方式。用display.precision控制小数位数见上文 5.6可结合大规模量级观察其效果import numpy as np pd.set_option(display.precision, 2) s pd.Series(np.random.randn(5), index[a, b, c, d, e]) s / 1.0e3 s / 1.0e6注意display.precision只影响显示不影响存储与计算。如果需要针对单个 DataFrame 的特定列做舍入应使用DataFrame.round()方法如df.round(2)它与全局显示精度是两套不同的机制。另外pandas/core/config_init.py 中还注册了display.float_format默认None接受可调用对象——它可以传入一个接收浮点数、返回格式化字符串的 callable用于定制任意浮点输出格式如千分位、货币符号等官方建议参考formats.format.EngFormatter的实现模式。与该系列配套的还有display.memory_usageTrue/False/deep控制df.info()是否显示内存占用。七、Unicode formatting东亚宽字符对齐警告启用本节选项会使 DataFrame 与 Series 的打印性能显著下降约慢 2 倍仅在确实需要时使用。部分东亚国家的 Unicode 字符宽度相当于两个拉丁字符。当 DataFrame/Series 包含这类字符时默认输出模式可能无法正确对齐df pd.DataFrame({国籍: [UK, 日本], 名前: [Alice, しのぶ]}) df # 中文/日文列可能出现对齐错乱将display.unicode.east_asian_width设为Truepandas 就会逐字符检查其 East Asian Width 属性并正确对齐pd.set_option(display.unicode.east_asian_width, True) df代价是渲染时间比标准的len计算更长。此外宽度为 ambiguous模棱两可的 Unicode 字符——例如倒感叹号¡——其宽度取决于终端设置或编码可能是 1 个也可能是 2 个字符宽。display.unicode.ambiguous_as_wide选项用于处理这种歧义默认情况下False歧义字符如¡按宽度 1 计算df pd.DataFrame({a: [xxx, ¡¡], b: [yyy, ¡¡]}) df设为True后pandas 把这些字符按宽度 2 解释注意只有display.unicode.east_asian_width已启用时本选项才生效pd.set_option(display.unicode.ambiguous_as_wide, True) df但需要警惕如果该设置与你的终端实际行为不符反而会导致对齐错误。所以应根据实际终端环境谨慎设置。这两个选项的注册位置见 pandas/core/config_init.py默认值均为False验证器为is_bool。八、Table schema displayHTML 表格模式输出DataFrame和Series默认会发布一种Table Schema表示供支持该协议的富前端使用。可以通过display.html.table_schema选项全局启用pd.set_option(display.html.table_schema, True)启用后只有display.max_rows所允许的行数会被序列化并发布。该选项默认False注册时绑定了一个回调table_schema_cbpandas/core/config_init.py它会在选项值变化时调用pandas.io.formats.printing.enable_data_resource_formatter来注册/注销数据资源 formatter——这正是选项回调机制cb的典型应用选项值被 set/reset 后立即触发副作用。九、源码级原理选项系统是如何工作的9.1 三个元数据容器整个选项系统的核心在 pandas/_config/config.py_global_config: dict—— 嵌套字典保存所有选项的当前值也是pd.options直接包装的对象_registered_options: dict[str, RegisteredOption]—— 保存每个选项的元数据key、默认值defval、文档doc、验证器validator、回调cb_deprecated_options: dict[str, DeprecatedOption]—— 保存已废弃选项的元数据警告类别、替换键rkey、移除版本等。读取选项的路径是get_option(pat)→_get_single_key正则匹配唯一键、处理废弃警告、翻译重定向键→_get_root沿点分路径走嵌套字典→ 返回叶子值。写入选项时_set_option_impl会先执行validator(v)校验新值再写入最后触发cb(key)回调。9.2 验证器validator与回调cb验证器保证了选项值永远合法。仓库内置了一批开箱即用的验证器工厂pandas/_config/config.py验证器作用is_type_factory(type)要求type(x) _typeis_instance_factory(type)要求isinstance(x, type)is_one_of_factory([...])要求值属于给定的合法集合支持 callable 成员is_nonnegative_int非负整数或Noneis_int/is_bool/is_float/is_str/is_text/is_callable常用类型的快捷验证器例如display.max_rows用is_nonnegative_intdisplay.large_repr用is_one_of_factory([truncate, info])io.excel.xlsx.reader用is_one_of_factory([*_xls_options, auto])。测试见 pandas/tests/config/test_config.py传入非法值1.1时会抛出带Value must be one of ...消息的ValueError。回调cb则在选项值变化后触发副作用典型例子包括compute.use_bottleneck的回调调用nanops.set_use_bottleneck(...)compute.use_numexpr的回调调用expressions.set_use_numexpr(...)plotting.matplotlib.register_converters的回调注册/注销 matplotlib 时间转换器见 pandas/core/config_init.py 与 L676-L695。这意味着你可以在运行时动态开关加速引擎无需重启进程。9.3 选项的分类注册与 config_prefixpandas/core/config_init.py 在 pandas 包导入时import pandas即触发见 pandas/init.py完成全部内置选项注册并按命名空间分组compute.*use_bottleneck默认 True、use_numexpr默认 True、use_numba默认 False——控制是否使用可选的加速库display.*前文详述的所有展示选项mode.*sim_interactive默认 False调试用、copy_on_write默认值由环境变量PANDAS_COPY_ON_WRITE决定可取值 True/False/warn、max_threads默认 None即min(os.cpu_count(), 4)、string_storageauto/python/pyarrow等io.excel.*.reader/writer如io.excel.xls.readerauto/xlrd/calamine、io.excel.xlsx.writerauto/openpyxl/xlsxwriter用于为各扩展名指定默认 Excel 引擎io.parquet.engineauto/pyarrow/fastparquet与io.sql.engineauto/sqlalchemyplotting.backend默认matplotlib可替换为任意实现了后端协议的模块名与plotting.matplotlib.register_convertersstyler.*sparse.index、render.max_elements默认2**18、format.precision默认 6、latex.*等大量 Styler 渲染选项future.*由_register_future_option注册的未来行为开关如future.infer_string、future.python_scalars并支持通过PANDAS_FUTURE/PANDAS_FUTURE_NAME环境变量在 CI 中统一切换 legacy/default/upcoming 三档行为pandas/core/config_init.py。注册代码大量使用with cf.config_prefix(display):这种上下文管理器pandas/_config/config.py来批量注册同一命名空间下的选项避免重复书写前缀——注意官方 docstring 明确说明它不是线程安全的且不适用于from x import y的导入方式。9.4 选项的废弃deprecation与重定向deprecate_option(key, category, msg, rkey, removal_ver)用于标记废弃选项。当前仓库中已注册的废弃选项包括pandas/core/config_init.pyfuture.no_silent_downcastingPandas4Warningfuture.infer_string——自 pandas 3.0 起字符串默认推断为 str dtype该开关将于 pandas 4.0 移除mode.copy_on_write——自 pandas 3.0 起 Copy-on-Write 总是启用、无法关闭此选项已无效果mode.chained_assignment——pandas 3.0 移除了SettingWithCopyWarning该选项不再生效建议改用warnings.filterwarningsChainedAssignmentError类别控制告警。废弃选项被引用时会触发警告若指定了rkey重定向键get/set/reset 都会自动转写到新键_translate_key与_warn_if_deprecated逻辑见 pandas/_config/config.py。9.5 错误类型与测试保障访问不存在的选项或匹配多个键时抛出OptionError它同时继承AttributeError与KeyError保证与旧代码的KeyError检查兼容pandas/_config/config.py并已映射到pandas.errors命名空间。整套 API 的行为由 pandas/tests/config/test_config.py637 行系统覆盖包括 API 存在性断言test_api、重复注册/前缀冲突/关键字命名检查test_register_option、描述输出test_describe_option等。测试通过 monkeypatch 将_global_config、options、_deprecated_options、_registered_options全部清空构造隔离环境验证注册与读写语义——这也侧面印证了_global_config等容器确实是整个系统的数据源。十、实战建议小结日常交互把常用选项写进 IPython startup 脚本$IPYTHONDIR/profile_default/startup下的.py/.ipy文件例如pd.set_option(display.max_rows, 999)与pd.set_option(display.precision, 5)。临时调整优先使用with pd.option_context(...)包裹代码段异常安全且不污染全局状态。完整命名除非在交互式环境下临时使用代码中始终写全选项名如display.max_rows规避未来新增同名选项导致的歧义报错。性能敏感场景谨慎启用display.unicode.east_asian_width打印慢约 2 倍大数据集上合理设置display.max_info_rows可显著加速df.info()。引擎调优通过compute.use_bottleneck/compute.use_numexpr动态开关加速库通过io.parquet.engine、io.excel.xlsx.reader等选项指定默认 IO 引擎通过plotting.backend切换绘图后端——这一切都无需修改业务代码。pandas 的选项系统把全局行为配置收敛为一个统一、可校验、可回滚、可枚举的 API是理解 pandas 显示层与运行时可配置行为的钥匙。【免费下载链接】pandasFlexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more项目地址: https://gitcode.com/gh_mirrors/pa/pandas创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门