pandasのオプション設定を確認・変更する方法

Posted: | Tags: Python, pandas

pandasではオプションの設定を変更することで動作や表示をカスタマイズできる。各種設定値を確認および変更する方法を説明する。

公式ドキュメントの説明ページは以下。

ここでは以下の内容について説明する。

  • 属性にアクセスして設定値を確認・変更: options
  • 設定情報を一覧で表示: describe_option()
  • 関数で設定値を確認・変更: get_option(), set_option()
  • 複数の設定値を一括で確認・変更
  • デフォルトの設定値に戻す: reset_option()
  • withブロック内で一時的に設定を変更: option_context()

実際に表示設定をカスタマイズする例は以下の記事を参照。

なお、設定の変更は同一コード(スクリプト)内でのみ有効。恒久的に書き換わるわけではなく、別のコードではまたデフォルト設定が使われる。

今回のサンプルコードのpandasのバージョンは以下の通り。なおpprintは表示を見やすくするために使っている。

import pandas as pd
import pprint

print(pd.__version__)
# 0.23.0

属性にアクセスして設定値を確認・変更: options

pd.options以下の属性で各設定値にアクセスして確認・変更できる。

print(pd.options.display.max_rows)
# 60

pd.options.display.max_rows = 100

print(pd.options.display.max_rows)
# 100

Jupyter Notebookや補完が効くエディタではTABキーなどで補完候補が表示されるので便利。

組み込み関数dir()で直下にどんな項目があるかを確認することも可能。

print(dir(pd.options))
# ['compute', 'display', 'html', 'io', 'mode', 'plotting']

pprint.pprint(dir(pd.options.display))
# ['chop_threshold',
#  'colheader_justify',
#  'column_space',
#  'date_dayfirst',
#  'date_yearfirst',
#  'encoding',
#  'expand_frame_repr',
#  'float_format',
#  'html',
#  'large_repr',
#  'latex',
#  'max_categories',
#  'max_columns',
#  'max_colwidth',
#  'max_info_columns',
#  'max_info_rows',
#  'max_rows',
#  'max_seq_items',
#  'memory_usage',
#  'multi_sparse',
#  'notebook_repr_html',
#  'pprint_nest_depth',
#  'precision',
#  'show_dimensions',
#  'unicode',
#  'width']

設定情報を一覧で表示: describe_option()

各設定項目の内容の説明とデフォルト値および現在の値はpd.describe_option()関数で表示できる。

内容の説明はドキュメントにも記載されている。

引数を省略するとすべての設定項目の情報が表示される。量が多いのでここでは出力は省略する。

pd.describe_option()

引数には正規表現パターンの文字列を指定する。パターンにマッチした設定項目の情報が表示される。

正規表現の特殊文字を使わずただの文字列を指定するとその文字列を含む設定項目が表示される。

pd.describe_option('compute')
# compute.use_bottleneck : bool
#     Use the bottleneck library to accelerate if it is installed,
#     the default is True
#     Valid values: False,True
#     [default: True] [currently: True]
# compute.use_numexpr : bool
#     Use the numexpr library to accelerate computation if it is installed,
#     the default is True
#     Valid values: False,True
#     [default: True] [currently: True]

pd.describe_option('max_col')
# display.max_columns : int
#     If max_cols 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 width of the terminal and print a truncated object which fits
#     the screen width. 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: 20] [currently: 20]
# display.max_colwidth : int
#     The maximum width in characters of a column in the repr of
#     a pandas data structure. When the column overflows, a "..."
#     placeholder is embedded in the output.
#     [default: 50] [currently: 50]

各設定項目の末尾の[default: xxx] [currently: xxx]がデフォルト値と現在の値。

正規表現の特殊文字を使ってもOK。

pd.describe_option('max.*col')
# display.max_columns : int
#     If max_cols 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 width of the terminal and print a truncated object which fits
#     the screen width. 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: 20] [currently: 20]
# display.max_colwidth : int
#     The maximum width in characters of a column in the repr of
#     a pandas data structure. When the column overflows, a "..."
#     placeholder is embedded in the output.
#     [default: 50] [currently: 50]
# display.max_info_columns : int
#     max_info_columns is used in DataFrame.info method to decide if
#     per column information will be printed.
#     [default: 100] [currently: 100]

関数で設定値を確認・変更: get_option(), set_option()

上述の属性による設定値へのアクセスのほかに、関数による確認・変更も可能。

現在の設定値を返す関数はpd.get_option()

引数には正規表現パターンの文字列を指定する。パターンにマッチした設定項目の現在の値が返される。

print(pd.get_option('display.max_rows'))
# 100

設定値を変更する関数はpd.set_option()

第一引数に正規表現パターンの文字列、第二引数に設定する値を指定する。パターンにマッチした設定項目の値が指定した値に変更される。

pd.set_option('display.max_rows', 60)

正規表現パターンによる指定なのでフルの項目名を指定しなくてもいいが、複数項目にマッチするとエラーOptionErrorになる。

print(pd.get_option('max_r'))
# 60

pd.set_option('max_r', 100)

# pd.get_option('max')
# OptionError: 'Pattern matched multiple keys'

# pd.set_option('max', 60)
# OptionError: 'Pattern matched multiple keys'

フルの項目名以外で指定した場合、将来、新規で追加された項目にマッチするとエラーになってしまう可能性があるので、長く使うコードではフルの項目名にしておいたほうが無難。

複数の設定値を一括で確認・変更

上述のように、属性を使った方法や関数get_option(), set_option()は一度に一つの設定値にしかアクセスできず、公式には複数の設定値を一括で確認・変更する方法はない。

コードとしての可読性は良くないが、参考までに複数の設定値を一括で確認・変更する方法を示す。以下のページを参考にした。

項目名のリストから複数の設定値を一括で確認する。リスト内包表記や辞書内包表記を使う。

l = ['display.max_rows', 'display.max_columns', 'display.max_colwidth']

print([pd.get_option(i) for i in l])
# [100, 20, 50]

print({i: pd.get_option(i) for i in l})
# {'display.max_rows': 100, 'display.max_columns': 20, 'display.max_colwidth': 50}

項目名と設定したい値の辞書から複数の設定値を一括で変更・確認する。辞書のメソッドitems(), keys()を使う。

d = {'display.max_rows': 80,
     'display.max_columns': 80,
     'display.max_colwidth': 80}

[pd.set_option(k, v) for k, v in d.items()]

print({i: pd.get_option(i) for i in d.keys()})
# {'display.max_rows': 80, 'display.max_columns': 80, 'display.max_colwidth': 80}

デフォルトの設定値に戻す: reset_option()

デフォルトの設定値に戻す関数はreset_option()

引数には正規表現パターンの文字列を指定する。パターンにマッチした設定項目の値がデフォルト値にリセットされる。

print(pd.options.display.max_rows)
# 80

pd.reset_option('display.max_rows')

print(pd.options.display.max_rows)
# 60

複数項目にマッチしてもOK。マッチしたすべての項目がリセットされる。

print(pd.options.display.max_columns)
print(pd.options.display.max_colwidth)
# 80
# 80

pd.reset_option('max_col')

print(pd.options.display.max_columns)
print(pd.options.display.max_colwidth)
# 20
# 50

先頭と一致する正規表現の特殊文字^を使ってdisplayのすべての項目をリセットする、というようなことも可能。

pd.options.display.max_rows = 100
pd.options.display.max_columns = 100
pd.options.display.max_colwidth = 100

pd.reset_option('^display', silent=True)

print(pd.options.display.max_rows)
print(pd.options.display.max_columns)
print(pd.options.display.max_colwidth)
# 60
# 20
# 50

引数を'all'とするとすべての項目がリセットされる。すべての項目にアクセスするのでバージョンによってはFutureWarningが出る。

pd.reset_option('all')
# html.border has been deprecated, use display.html.border instead
# (currently both are identical)
# : boolean
#     use_inf_as_null had been deprecated and will be removed in a future
#     version. Use `use_inf_as_na` instead.
# /usr/local/lib/python3.6/site-packages/pandas/core/config.py:619: FutureWarning: html.border has been deprecated, use display.html.border instead
# (currently both are identical)
#   warnings.warn(d.msg, FutureWarning)
# /usr/local/lib/python3.6/site-packages/pandas/core/config.py:619: FutureWarning: 
# : boolean
#     use_inf_as_null had been deprecated and will be removed in a future
#     version. Use `use_inf_as_na` instead.
#   warnings.warn(d.msg, FutureWarning)

FutureWarningを出力させたくない場合は引数silent=Trueを合わせて指定する。

pd.reset_option('all', silent=True)

withブロック内で一時的に設定を変更: option_context()

withブロックでpd.option_context()を使うと、そのブロック内でのみ設定が変更される。

第一引数に正規表現パターンの文字列、第二引数に設定する値を指定する。パターンにマッチした設定項目の値が指定した値に変更される。

withブロックの中でのみ設定が変更され、ブロックを抜けると元の値に戻る。

with pd.option_context('display.max_rows', 100):
    print(pd.options.display.max_rows)
# 100

print(pd.options.display.max_rows)
# 60

デフォルト値に戻るのではなく、withブロックに入る前の値に戻る。

pd.options.display.max_rows = 80

with pd.option_context('display.max_rows', 100):
    print(pd.options.display.max_rows)
# 100

print(pd.options.display.max_rows)
# 80

(pat, val, pat, val, ...)と正規表現パターンの文字列と設定値を繰り返し引数に指定することで複数の設定項目を変更できる。

with pd.option_context('display.max_rows', 100, 'display.max_columns', 100):
    print(pd.options.display.max_rows)
    print(pd.options.display.max_columns)
# 100
# 100

print(pd.options.display.max_rows)
print(pd.options.display.max_columns)
# 80
# 20

withブロックの外でpd.option_context()を使っても値は変更されない。

pd.option_context('display.max_rows', 100)

print(pd.options.display.max_rows)
# 80

関連カテゴリー

関連記事