Python Pandas 选项和自定义


Pandas 提供 API 来自定义其行为的某些方面,主要使用显示。

API 由五个相关函数组成。他们是:

  • get_option()

  • set_option()

  • reset_option()

  • describe_option()

  • option_context()

现在让我们了解这些功能是如何运作的。

get_option(param)


get_option 接受单个参数并返回如下输出中给出的值:

display.max_rows

显示默认值的数量。解释器读取此值并将具有此值的行显示为要显示的上限。

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

输出如下:

60

display.max_columns

显示默认值的数量。解释器读取此值并将具有此值的行显示为要显示的上限。

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

输出如下:

20

此处,60 和 20 是默认配置参数值。

set_option(param,value)


set_option 接受两个参数并将值设置为参数,如下所示:

display.max_rows

使用set_option(),我们可以更改要显示的默认行数。

import pandas as pd

pd.set_option("display.max_rows",80)

print pd.get_option("display.max_rows")

输出如下:

80

display.max_columns

使用set_option(),我们可以更改要显示的默认行数。

import pandas as pd

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

print pd.get_option("display.max_columns")

输出如下:

30

reset_option(param)


reset_option接受一个参数并将值设置回默认值。

display.max_rows

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

import pandas as pd

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

输出如下:

60

describe_option(param)


describe_option打印参数的描述。

display.max_rows

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

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()


option_context上下文管理器用于临时设置with语句中的选项,当退出with块时,选项值会自动恢复。

display.max_rows

使用 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
10

第一个语句打印的是option_context()设置的值,它在with context本身中是暂时的。在with上下文之后,第二个打印语句打印的是配置的值。

常用参数

序号参数及说明
1

display.max_rows

显示要显示的最大行数

2

2 display.max_columns

显示要显示的最大列数

3

display.expand_frame_repr

显示数据帧以拉伸页面

4

display.max_colwidth

显示最大列宽

5

display.precision

显示十进制数的精度