Skip to content

pandas: Ottenere e impostare opzioni per la visualizzazione, il comportamento dei dati, ecc.

Python

Nei panda, puoi personalizzare il comportamento globale, come il formato di visualizzazione, impostando le opzioni.

In questo articolo vengono descritti i seguenti contenuti.

  • Ottieni e imposta i valori delle opzioni con l’attributo:options
  • Stampa la descrizione per le opzioni:describe_option()
  • Ottieni e imposta i valori delle opzioni con le funzioni:get_option(), set_option()
  • Ottieni e più valori di opzione
  • Ripristina le opzioni ai valori predefiniti:reset_option()
  • Modifica temporaneamente le impostazioni con:option_context()

Nota che la modifica delle opzioni non le riscrive in modo permanente; un altro codice utilizza nuovamente le impostazioni predefinite.

La versione panda in questo codice di esempio è la seguente. Si noti che pprint utilizzato viene per semplificare la lettura del display.

import pandas as pd
import pprint

print(pd.__version__)
# 0.23.0

Ottieni e imposta i valori delle opzioni con l’attributo:options

È possibile ottenere e impostare i valori delle opzioni tramite gli attributi in pd.options.

print(pd.options.display.max_rows)
# 60

pd.options.display.max_rows = 100

print(pd.options.display.max_rows)
# 100

Puoi controllare quali elementi sono disponibili con la funzione dir() incorporata.

print(dir(pd.options))
# ['compute', 'display', 'html', 'io', 'mode', 'plotting']

pprint.pprint(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',
#  'multi_sparse',
#  'notebook_repr_html',
#  'pprint_nest_depth',
#  'precision',
#  'show_dimensions',
#  'unicode',
#  'width']

Stampa la descrizione per le opzioni:describe_option()

È possibile stampare la descrizione, il valore predefinito e corrente di ciascuna opzione con la funzione pd.describe_option().

Se l’argomento viene omesso, vengono visualizzate le informazioni su tutte le opzioni. L’uscita viene omesso qui.

È possibile specificare una stringa del modello di espressione regolare per il primo argomento. Possono essere disponibili le opzioni relative al motivo. [predefinito: xxx] [attualmente: xxx] rappresenta i valori predefiniti e correnti.

pd.describe_option('max.*col')
# display.max_columns : int
#     If max_cols 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 width of the terminal and print a truncated object which fits
#     the screen width. 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: 20] [currently: 20]
# display.max_colwidth : int
#     The maximum width in characters of a column in the repr of
#     a pandas data structure. When the column overflows, a "..."
#     placeholder is embedded in the output.
#     [default: 50] [currently: 50]
# display.max_info_columns : int
#     max_info_columns is used in DataFrame.info method to decide if
#     per column information will be printed.
#     [default: 100] [currently: 100]

Se si specifica solo una stringa senza caratteri speciali dell’espressione regolare, vengono lasciate le opzioni che contengono la stringa.

pd.describe_option('compute')
# compute.use_bottleneck : bool
#     Use the bottleneck library to accelerate if it is installed,
#     the default is True
#     Valid values: False,True
#     [default: True] [currently: True]
# compute.use_numexpr : bool
#     Use the numexpr library to accelerate computation if it is installed,
#     the default is True
#     Valid values: False,True
#     [default: True] [currently: True]

pd.describe_option('max_col')
# display.max_columns : int
#     If max_cols 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 width of the terminal and print a truncated object which fits
#     the screen width. 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: 20] [currently: 20]
# display.max_colwidth : int
#     The maximum width in characters of a column in the repr of
#     a pandas data structure. When the column overflows, a "..."
#     placeholder is embedded in the output.
#     [default: 50] [currently: 50]

Ottieni e imposta i valori delle opzioni con le funzioni:get_option(), set_option()

Puoi anche ottenere e impostare valori con le funzioni.

pd.get_option() fornisce il valore dell’opzione corrente.

print(pd.get_option('display.max_rows'))
# 100

È possibile impostare il valore dell’opzione con pd.set_option().

pd.set_option('display.max_rows', 60)

È possibile specificare un modello di espressione regolare come argomento. Non è necessario specificare il nome completo dell’elemento, ma la corrispondenza di più elementi generi OptionError.

print(pd.get_option('max_r'))
# 60

pd.set_option('max_r', 100)

# pd.get_option('max')
# OptionError: 'Pattern matched multiple keys'

# pd.set_option('max', 60)
# OptionError: 'Pattern matched multiple keys'

Ottieni e più valori di opzione

Le funzioni per ottenere e impostare più valori di opzione non sono fornite.

Questa sezione mostra come ottenere e impostare più valori di opzione con la comprensione degli elenchi, ecc.

Ottieni i valori delle opzioni dei nomi degli elementi elencati con la comprensione dell’elenco e dei dettati.

l = ['display.max_rows', 'display.max_columns', 'display.max_colwidth']

print([pd.get_option(i) for i in l])
# [100, 20, 50]

print({i: pd.get_option(i) for i in l})
# {'display.max_rows': 100, 'display.max_columns': 20, 'display.max_colwidth': 50}

Imposta i valori delle opzioni in base al dizionario dei nomi degli elementi e al valore con i metodi del dizionario, items() e keys().

d = {'display.max_rows': 80,
     'display.max_columns': 80,
     'display.max_colwidth': 80}

[pd.set_option(k, v) for k, v in d.items()]

print({i: pd.get_option(i) for i in d.keys()})
# {'display.max_rows': 80, 'display.max_columns': 80, 'display.max_colwidth': 80}

Ripristina le opzioni ai valori predefiniti:reset_option()

reset_option() ripristina le opzioni ai valori predefiniti.

È possibile specificare una stringa del modello di espressione regolare.

print(pd.options.display.max_rows)
# 80

pd.reset_option('display.max_rows')

print(pd.options.display.max_rows)
# 60

Se più elementi vengono abbinati, tutti gli elementi vengono reimpostati.

print(pd.options.display.max_columns)
print(pd.options.display.max_colwidth)
# 80
# 80

pd.reset_option('max_col')

print(pd.options.display.max_columns)
print(pd.options.display.max_colwidth)
# 20
# 50

Ad esempio, puoi reimpostare tutte le opzioni visualizzate con il carattere speciale dell’espressione regolare ^ che corrisponde all’inizio.

pd.options.display.max_rows = 100
pd.options.display.max_columns = 100
pd.options.display.max_colwidth = 100

pd.reset_option('^display', silent=True)

print(pd.options.display.max_rows)
print(pd.options.display.max_columns)
print(pd.options.display.max_colwidth)
# 60
# 20
# 50

“tutto” reimposta tutti gli elementi.

pd.reset_option('all')
# html.border has been deprecated, use display.html.border instead
# (currently both are identical)
# : boolean
#     use_inf_as_null had been deprecated and will be removed in a future
#     version. Use `use_inf_as_na` instead.
# /usr/local/lib/python3.6/site-packages/pandas/core/config.py:619: FutureWarning: html.border has been deprecated, use display.html.border instead
# (currently both are identical)
#   warnings.warn(d.msg, FutureWarning)
# /usr/local/lib/python3.6/site-packages/pandas/core/config.py:619: FutureWarning: 
# : boolean
#     use_inf_as_null had been deprecated and will be removed in a future
#     version. Use `use_inf_as_na` instead.
#   warnings.warn(d.msg, FutureWarning)

Se non si desidera che FutureWarning venga emesso, specificare silent=True.

pd.reset_option('all', silent=True)

Modifica temporaneamente le impostazioni con:option_context()

Con pd.option_context(), le impostazioni vengono modificate solo nel blocco con.

with pd.option_context('display.max_rows', 100):
    print(pd.options.display.max_rows)
# 100

print(pd.options.display.max_rows)
# 60

Non viene ripristinato al valore di default, ma ritorna al valore precedente al blocco con.

pd.options.display.max_rows = 80

with pd.option_context('display.max_rows', 100):
    print(pd.options.display.max_rows)
# 100

print(pd.options.display.max_rows)
# 80

È possibile più elementi specificando una stringa del modello di espressione regolare e un nuovo valore come (pat, val, val, …).

with pd.option_context('display.max_rows', 100, 'display.max_columns', 100):
    print(pd.options.display.max_rows)
    print(pd.options.display.max_columns)
# 100
# 100

print(pd.options.display.max_rows)
print(pd.options.display.max_columns)
# 80
# 20