Quantcast
Channel: kakakakakku blog
Viewing all articles
Browse latest Browse all 920

Jupyter Notebook と Pandas で DataFrame を全て表示するオプション設定

$
0
0

Jupyter NotebookPandasのコードを実装しているときに同じような表示関連設定を繰り返し使うため,メモも兼ねてまとめておく.オプションは他にも多くあり,詳細はドキュメントに載っている.今回は Python 3.9Pandas 1.2.4を前提とする.

pandas.pydata.org

オプション一覧を取得する 🎯

まず,Pandas では optionsでオプション一覧(名前空間)を取得できる.例えば displayなど.また options.displayでオプション一覧(display名前空間)を取得できる.例えば chop_thresholdcolheader_justifyなど多くある.

dir(pd.options)
# ['compute', 'display', 'io', 'mode', 'plotting']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',#  'min_rows',#  'multi_sparse',#  'notebook_repr_html',#  'pprint_nest_depth',#  'precision',#  'show_dimensions',#  'unicode',#  'width']

次に get_option()関数を使うと,オプション値を取得できる.以下では「表示する最低行数 display.min_rows「表示する最大行数 display.max_rows「表示する最大カラム数 display.max_columnsのオプション値をサンプルとして取得している.なお,今回はデフォルト値として取得している.

pd.get_option('display.min_rows')
# 10
pd.get_option('display.max_rows')
# 60
pd.get_option('display.max_columns')
# 20

また describe_option()関数を使うと,オプションごとに詳細な説明文やデフォルト値を確認できる.便利!

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]

DataFrame を全て表示する 🎯

Pandas で DataFrameを表示すると,以下のようにデフォルトでは省略される.表示する行数に関連するオプションは display.min_rowsdisplay.max_rowsで,データセットの行数が display.max_rowsを超える場合は display.min_rowsを表示するため,今回は「10行」表示されている.なお,今回は GitHub リポジトリ chendaniely/pandas_for_everyoneに含まれているデータセット wine.csvを使う.

wine = pd.read_csv('./wine.csv')
wine

f:id:kakku22:20210414225022p:plain

そこで set_option()関数を使って,オプション値を上書きする.display.max_rowsdisplay.max_columnsNoneを設定すると「上限なし」となり,DataFrameを省略せずに全て表示できるようになる(以下は 20 行目まで載せている).

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
wine

f:id:kakku22:20210414225948p:plain

まとめ 🎯

Jupyter NotebookPandasのコードを実装しているときに DataFrameを全て表示するオプションを繰り返し使っていたため,メモも兼ねてまとめておくことにした.引き続き Pandasを試すぞー👌

pandas.pydata.org


Viewing all articles
Browse latest Browse all 920

Trending Articles