pandasでブロック内だけで小数点以下の表示数を変更するの巻

はじめに
Pythonのpandasで小数点以下の表示数を変更したいときは、
pd.options.display.float_format = ‘{:.2f}’.format
のように記述しておけばいいけど、この方法だとスクリプト全体に適用されます。
では一時的に、任意のブロックの中でだけ小数点以下の表示数を変更したい時はどうしたらいいのん?
てなったのでやり方をメモ。
やり方
with pd.option_context(‘display.float_format’, ‘{:.2f}’.format):
のように、with構文中でpd.option_contextの’display.float_format’を設定してやることで、ブロックの中だけで小数点以下の表示数を変更できます。
とりあえず使用するDataFrameをば作成。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3,3))
display(df)

ではやってみます。
withを使います。小数点以下の表示桁数を0にしてみました。
with pd.option_context('display.float_format', '{:.0f}'.format):
display(df)
display(df)

でけた。withから出たところではちゃんと元どおりの表示になっています。
ちなみに、withを使う時は、pd.optionsではinvalid syntaxのエラーが出てしまうので、pd.option_contextで変更しないといけないみたい。
他のオプションにおいてもwithの中でpd.option_contextを使うことで一時的な設定変更がうまくいくはず(知らんけど)。
環境
この記事の内容は
Python; 3.7.2
pandas; 1.0.5
jupyter; 1.0.0
にて実施しました。
このブログはエックスサーバー


WordPressを使うならロリポップ!
簡単インストール完備で楽々スタート!

世界にたった一つ、あなただけのドメインを登録しよう!
格安ドメイン取得サービス─ムームードメイン─
