Python Pandas - 选项和自定义



Pandas 提供了一个 API 来自定义其行为的各个方面,尤其是在显示设置方面。这种自定义对于根据您的需求调整数据呈现方式至关重要。无论您是想调整显示的行数和列数,还是更改浮点数的精度,Pandas 都为这些自定义提供了灵活而强大的 API。

可用于这些自定义的主要函数有:

  • get_option()
  • set_option()
  • reset_option()
  • describe_option()
  • option_context()

常用参数

在了解自定义选项之前,让我们先了解一些您可以用于自定义的常用 Pandas 显示参数:

序号 参数和描述
1

display.max_rows

要显示的最大行数。

2

2 display.max_columns

要显示的最大列数。

3

display.expand_frame_repr

是否在多行上扩展 DataFrame 的显示。

4

display.max_colwidth

列的最大宽度。

5

display.precision

显示十进制数字的精度。

现在让我们了解自定义函数是如何工作的。

获取当前选项

get_option() 函数检索指定参数的当前值。这对于检查 Pandas 的当前配置很有用。

示例:检查显示的最大行数

以下示例获取并返回显示的最大行数的默认值。解释器读取此值并以该值为显示上限显示行。

import pandas as pd
print(pd.get_option("display.max_rows"))

输出如下:

60

示例:检查显示的最大列数

此示例返回显示的最大列数的默认值。解释器读取此值并以该值为显示上限显示行。

import pandas as pd
print(pd.get_option("display.max_columns"))

输出如下:

0

这里,60 和 0 是默认配置参数值。

设置新选项

set_option() 函数允许您更改特定参数的值,使您可以自定义数据显示方式。

示例:更改显示的最大行数

使用set_option(),我们可以更改要显示的行数的默认值。这是一个例子:

import pandas as pd
pd.set_option("display.max_rows",10)
print(pd.get_option("display.max_rows"))

输出如下:

10

示例:更改显示的最大列数

以下示例使用set_option() 函数更改要显示的列数的默认值。

import pandas as pd

pd.set_option("display.max_columns",30)

print(pd.get_option("display.max_columns"))

输出如下:

30

将选项重置为其默认值

reset_option() 函数将指定参数的值重置回其默认设置。

示例:重置显示的最大行数

使用reset_option() 函数,我们可以将值更改回要显示的行数的默认值。

import pandas as pd

pd.reset_option("display.max_rows")
print(pd.get_option("display.max_rows"))

输出如下:

60

描述选项

describe_option() 函数提供指定参数的描述,解释其作用及其默认值。

示例:描述显示的最大行数

此示例使用reset_option() 函数获取max_row 参数的描述。

import pandas as pd
pd.describe_option("display.max_rows")

输出如下:

display.max_rows : int
   If max_rows is exceeded, switch to truncate view. Depending on
   'large_repr', objects are either centrally truncated or printed as
   a summary view. 'None' value means unlimited.

   In case python/IPython is running in a terminal and `large_repr`
   equals 'truncate' this can be set to 0 and pandas will auto-detect
   the height of the terminal and print a truncated object which fits
   the screen height. The IPython notebook, IPython qtconsole, or
   IDLE do not run in a terminal and hence it is not possible to do
   correct auto-detection.
   [default: 60] [currently: 60]

临时选项设置

option_context() 函数允许您在with 语句中临时设置选项。退出上下文后,选项会自动恢复到其先前值。

示例:临时更改显示的最大行数

此示例使用option_context() 函数为要显示的最大行数设置临时值。

import pandas as pd
with pd.option_context("display.max_rows",10):
   print(pd.get_option("display.max_rows"))
print(pd.get_option("display.max_rows"))

输出如下:

10
60

请注意,第一个和第二个 print 语句之间的区别。第一个语句打印由option_context() 设置的值,该值在with 上下文本身中是临时的。在with 上下文之后,第二个 print 语句打印已配置的值。

广告

© . All rights reserved.