选项和设置#

概述#

pandas 提供了一个选项 API,用于配置和自定义与 DataFrame 显示、数据行为等相关的全局行为。

选项具有全“点状”的、不区分大小写的名称(例如 display.max_rows)。您可以直接将选项作为顶级 options 属性的属性来获取/设置:

API 由 5 个相关函数组成,可直接从 pandas 命名空间访问:

备注

开发人员可以查看 pandas/core/config_init.py 以获取更多信息。

所有上述函数都接受一个正则表达式模式(re.search 样式)作为参数,以匹配一个无歧义的子字符串: […]

以下将**不起作用**,因为它匹配多个选项名称,例如 display.max_colwidthdisplay.max_rowsdisplay.max_columns

警告

使用这种形式的简写可能会导致代码在未来版本添加具有相似名称的新选项时中断。

可用选项#

您可以使用 describe_option() 获取可用选项及其描述的列表。当不带参数调用时, describe_option() 将打印所有可用选项的描述。

获取和设置选项#

如上所述,get_option()set_option() 可从 pandas 命名空间访问。要更改选项,请调用 set_option('option regex', new_value)

备注

选项 'mode.sim_interactive' 主要用于调试目的。

您可以使用 reset_option() 来恢复到设置的默认值

一次重置多个选项(使用正则表达式)也是可能的:

option_context() 上下文管理器已通过顶级 API 公开,允许您使用给定的选项值执行代码。退出 with 块时,选项值会自动恢复:

在 Python/IPython 环境中设置启动选项#

为 Python/IPython 环境使用启动脚本导入 pandas 并设置选项可以使 pandas 的工作更高效。为此,请在所需配置文件的启动目录中创建一个 .py.ipy 脚本。有关启动文件夹位于默认 IPython 配置文件的示例,请参见:

$IPYTHONDIR/profile_default/startup

有关更多信息,请参阅 IPython documentation 。下面显示了一个 pandas 的示例启动脚本:

import pandas as pd

pd.set_option("display.max_rows", 999)
pd.set_option("display.precision", 5)

常用选项#

以下演示了更常用的显示选项。

display.max_rowsdisplay.max_columns 设置了在进行 DataFrame 的“pretty-print”时显示的行数和列数上限。截断的行将被省略号替换。

一旦超过 display.max_rowsdisplay.min_rows 选项将决定在截断的 repr 中显示多少行。

display.expand_frame_repr 允许 DataFrame 的表示形式跨越页面,并围绕所有列进行换行。

display.large_repr 以截断的框架或摘要的形式显示超过 max_columnsmax_rowsDataFrame

display.max_colwidth 设置列的最大宽度。长度等于或大于此值的单元格将被截断并加上省略号。

display.max_info_columns 设置调用 info() 时显示的列数的阈值。

display.max_info_rowsinfo() 通常会显示每列的 null 计数。对于大型 DataFrame ,这可能会非常慢。max_info_rowsmax_info_cols 分别将此 null 检查限制为指定的行和列。info() 关键字参数 show_counts=True 将覆盖此设置。

display.precision 按小数位数设置输出显示精度。

display.chop_threshold sets the rounding threshold to zero when displaying a Series or DataFrame. This setting does not change the precision at which the number is stored.

数字格式化

pandas 还允许您设置数字在控制台中如何显示。此选项不是通过 set_options API 设置的。#

使用 set_eng_float_format 函数来更改 pandas 对象的浮点数格式,以生成特定格式。

使用 round() 来专门控制单个 DataFrame 的舍入。

Use round() to specifically control rounding of an individual DataFrame

启用此选项会影响 DataFrame 和 Series 的打印性能(大约慢 2 倍)。仅在确实需要时使用。#

警告

一些东亚国家使用宽度相当于两个拉丁字符的 Unicode 字符。如果 DataFrame 或 Series 包含这些字符,默认的输出模式可能无法正确对齐它们。

启用 display.unicode.east_asian_width 允许 pandas 检查每个字符的“东亚宽度”属性。通过将此选项设置为 True,可以正确对齐这些字符。但是,这会导致渲染时间比标准的 len 函数长。

此外,宽度为“模糊”的 Unicode 字符可以根据终端设置或编码成为 1 或 2 个字符宽。可以使用 display.unicode.ambiguous_as_wide 选项来处理这种模糊性。

默认情况下,“模糊”字符(如下面的示例中的“¡”(倒感叹号))的宽度被认为是 1。

启用 display.unicode.ambiguous_as_wide 会使 pandas 将这些字符的宽度解释为 2。(请注意,仅当启用了 display.unicode.east_asian_width 时,此选项才有效。)

但是,为您的终端错误地设置此选项将导致这些字符对齐不正确:

表模式显示

DataFrameSeries 默认会发布表模式表示。可以通过 display.html.table_schema 选项全局启用此功能:#

DataFrame and Series will publish a Table Schema representation by default. This can be enabled globally with the display.html.table_schema option:

PyArrow 功能