Pandas 自定義選項操作實例
Pandas因為提供了API來自定義行為,所以被廣泛使用。
自定義API中有五個相關(guān)功如下:
get_option()set_option()reset_option()describe_option()option_context()
下面我們一起了解下這些方法。
get_option接受一個參數(shù)并輸出以下值:
顯示默認(rèn)值的數(shù)量。解釋器讀取該值,并以該值作為顯示上限顯示行。
import pandas as pd print(pd.get_option("display.max_rows"))
運行結(jié)果:
60
顯示默認(rèn)值的數(shù)量。解釋器讀取該值,并以該值作為顯示上限顯示行。
import pandas as pd print(pd.get_option("display.max_columns"))
運行結(jié)果:
20
此處,60和20是默認(rèn)配置參數(shù)值。
set_option接受兩個參數(shù)并將值設(shè)置為參數(shù),如下所示:
使用set_option(),我們可以更改要顯示的默認(rèn)行數(shù)。
import pandas as pd pd.set_option("display.max_rows",80) print(pd.get_option("display.max_rows"))
運行結(jié)果:
80
使用set_option(),我們可以更改要顯示的默認(rèn)行數(shù)。
import pandas as pd pd.set_option("display.max_columns",30) print(pd.get_option("display.max_columns"))
運行結(jié)果:
30
reset_option 接受一個參數(shù)并將其設(shè)置回默認(rèn)值。
使用reset_option(),我們可以將值更改回要顯示的默認(rèn)行數(shù)。
import pandas as pd pd.reset_option("display.max_rows") print(pd.get_option("display.max_rows"))
運行結(jié)果:
60
describe_option 打印參數(shù)的描述
使用reset_option(),我們可以將值更改回要顯示的默認(rèn)行數(shù)。
import pandas as pd pd.describe_option("display.max_rows")
運行結(jié)果:
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上下文管理器用于臨時設(shè)置with語句中的選項。當(dāng)您退出with塊時,選項值會自動恢復(fù)。
使用option_context(),我們可以臨時設(shè)置值。
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"))
運行結(jié)果:
10 10
請參閱第一個和第二個打印語句之間的差異。第一條語句打印由option_context()設(shè)置的值,該值在with上下文本身中是臨時的。在with上下文之后,第二個print語句打印配置的值。
參數(shù) | 說明 |
display.max_rows | 顯示要顯示的最大行數(shù) |
display.max_columns< | 顯示要顯示的最大列數(shù) |
display.expand_frame_repr | 顯示數(shù)據(jù)框以拉伸頁面 |
display.max_colwidth | 顯示最大列寬 |
display.precision | 顯示十進(jìn)制數(shù)字的精度 |