pandas之設置顯示格式


在用 Pandas 做數據分析的過程中,總需要打印數據分析的結果,如果數據體量較大就會存在輸出內容不全(部分內容省略)或者換行錯誤等問題。Pandas 為了解決上述問題,允許你對數據顯示格式進行設置。下面列出了五個用來設置顯示格式的函數,分別是:

  • get_option()
  • set_option()
  • reset_option()
  • describe_option()
  • option_context()


它們的功能介紹如下:

函數名稱 說明
get_option 獲取解釋器的默認參數值。
set_option 更改解釋器的默認參數值。
reset_option 解釋器的參數重置為默認值。
describe_option 輸出參數的描述信息。
option_context 臨時設置解釋器參數,當退出使用的語句塊時,恢復為默認值。


下面對上述函數分別進行介紹。

get_option()

該函數接受單一參數,用來獲取顯示上限的行數或者列數,示例如下:

1) display.max_rows

獲取顯示上限的行數,示例如下:

  1. import pandas as pd
  2. print (pd.get_option("display.max_rows"))

輸出結果:

60

2) display.max_columns

獲取顯示上限的列數,示例如下:

  1. import pandas as pd
  2. print (pd.get_option("display.max_columns"))

輸出結果:

20

由此可知,默認值顯示上限是(60,20)。

set_option()

該函數用來更改要默認顯示的行數和列數,示例如下:

1) 修改默認行數

  1. import pandas as pd
  2. pd.set_option("display.max_rows",70)
  3. print (pd.get_option("display.max_rows"))

輸出結果:

70

2) 修改默認列數

  1. import pandas as pd
  2. pd.set_option("display.max_columns",40)
  3. print (pd.get_option("display.max_columns"))

輸出結果:

40

reset_option()

該方法接受一個參數,並將修改后的值設置回默認值。示例如下:

  1. import pandas as pd
  2. pd.reset_option("display.max_rows")
  3. #恢復為默認值
  4. print(pd.get_option("display.max_rows"))

輸出結果:

60

describe_option()

該方法輸出參數的描述信息。示例如下:

  1. import pandas as pd
  2. 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]

option_context()

option_context() 上下文管理器,用於臨時設置 with 語句塊中的默認顯示參數。當您退出 with 語句塊時,參數值會自動恢復。示例如下:

  1. import pandas as pd
  2. with pd.option_context("display.max_rows",10):
  3. print(pd.get_option("display.max_rows"))
  4. print(pd.get_option("display.max_rows"))

輸出結果:

10
60


注意:第一個 Print 語句打印 option_context() 設置的臨時值。當退出 with 語句塊時,第二個 Print 語句打印解釋器默認值。

常用參數項

最后,對上述函數常用的參數項做以下總結:

參數 說明
display.max_rows 最大顯示行數,超過該值用省略號代替,為None時顯示所有行。
display.max_columns 最大顯示列數,超過該值用省略號代替,為None時顯示所有列。
display.expand_frame_repr 輸出數據寬度超過設置寬度時,表示是否對其要折疊,False不折疊,True要折疊。
display.max_colwidth 單列數據寬度,以字符個數計算,超過時用省略號表示。
display.precision 設置輸出數據的小數點位數。
display.width 數據顯示區域的寬度,以總字符數計算。
display.show_dimensions 當數據量大需要以truncate(帶引號的省略方式)顯示時,該參數表示是否在最后顯示數據的維數,默認 True 顯示,False 不顯示。


上述參數項,基本上可以滿足我們的日常需求。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM