Pandas のオプションと設定

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Pandas DataFrameの表示、データの振る舞いなどに関連するグローバルな動作をどのように構成およびカスタマイズするかを理解することに焦点を当てています。オプションを取得/設定し、既定値にリセットし、オプションを説明する方法を探ります。また、実行後に以前の設定に戻る一連のオプションでコード ブロックを実行する方法も学びます。

VMのヒント

VMの起動が完了したら、左上隅をクリックしてノートブック タブに切り替え、Jupyter Notebookを使って練習しましょう。

時々、Jupyter Notebookが読み込み終了するまで数秒待つ必要がある場合があります。Jupyter Notebookの制限により、操作の検証を自動化することはできません。

学習中に問題が発生した場合は、Labbyにお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

Pandasのインポート

まずはPandasライブラリをインポートしましょう。これはPythonにおける強力なデータ操作ライブラリです。

## Importing pandas library
import pandas as pd

オプションの取得と設定

pd.get_option または pd.set_option をそれぞれ使用して、単一のオプションの値を取得または設定することができます。ここでは、最大表示行数を999に設定しています。

## Get the current setting for maximum display rows
print(pd.options.display.max_rows)

## Set the maximum display rows to 999
pd.options.display.max_rows = 999

## Verify the new setting
print(pd.options.display.max_rows)

オプションのリセット

1つ以上のオプションを既定値にリセットしたい場合は、pd.reset_option を使用できます。

## Reset the maximum display rows to default
pd.reset_option("display.max_rows")

## Verify the reset
print(pd.options.display.max_rows)

オプションの説明

1つ以上のオプションの説明を表示するには、pd.describe_option を使用します。

## Describe the 'display.max_rows' option
pd.describe_option("display.max_rows")

option_contextの使用

option_context 関数を使用すると、実行後に以前の設定に戻る一連のオプションでコード ブロックを実行できます。

## Execute a code block with a set of options
with pd.option_context("display.max_rows", 10):
    ## This will print 10 despite the global setting being different
    print(pd.get_option("display.max_rows"))

## This will print the global setting as the context block has ended
print(pd.get_option("display.max_rows"))

起動時のオプション設定

Python/IPython環境で起動スクリプトを作成して、pandasをインポートしてオプションを設定することができます。これにより、pandasの作業が効率的になります。

## This is an example of a startup script
## Place this in a.py file in the startup directory of IPython profile
import pandas as pd

pd.set_option("display.max_rows", 999)
pd.set_option("display.precision", 5)

まとめ

この実験ガイドでは、pandasにおけるオプションの取得、設定、およびリセット方法について説明しました。また、オプションの説明方法と option_context 関数の使用方法についても議論しました。最後に、Python/IPython環境での起動時オプションの設定方法を検討しました。これらの技術を使うことで、pandasの動作を必要に応じてカスタマイズして構成することができます。