
pandas.DataFrame ha il tipo di dati dtype per ogni colonna.
Per estrarre solo colonne con dtype specifico, usa il metodo select_dtypes() di pandas.DataFrame.
In questo articolo vengono descritti i seguenti contenuti.
- Utilizzo di base di select_dtypes()
- Specificare il tipo da estrarre:
include - Specificare il tipo da eseguire:
exclude
- Specificare il tipo da estrarre:
Vedere l’articolo seguente per il tipo di dati dtype e il metodo astype().
Usa il seguente pandas.DataFrame con colonne di vari tipi di dati come esempio.
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3],
'b': [0.1, 0.2, 0.3],
'c': ['X', 'Y', 'Z'],
'd': [[0, 0], [1, 1], [2, 2]],
'e': [True, True, False]})
df['f'] = pd.to_datetime(['2018-01-01', '2018-02-01', '2018-03-01'])
print(df)
# a b c d e f
# 0 1 0.1 X [0, 0] True 2018-01-01
# 1 2 0.2 Y [1, 1] True 2018-02-01
# 2 3 0.3 Z [2, 2] False 2018-03-01
print(df.dtypes)
# a int64
# b float64
# c object
# d object
# e bool
# f datetime64[ns]
# dtype: object
Utilizzo di base di select_dtypes()
Specificare il dtype da estrarre con il parametro include.
print(df.select_dtypes(include=int))
# a
# 0 1
# 1 2
# 2 3
I tipi predefiniti di Python come int e float possono essere specificati così come sono. Puoi anche specificarlo come una stringa, come ‘int’. Può anche essere come ‘int64’, includendo rigorosamente il numero di bit.
print(df.select_dtypes(include='int'))
# a
# 0 1
# 1 2
# 2 3
print(df.select_dtypes(include='int64'))
# a
# 0 1
# 1 2
# 2 3
Naturalmente, se il numero di bit è incluso, non verrà selezionato a meno che il numero di bit non corrisponda.
print(df.select_dtypes(include='int32'))
# Empty DataFrame
# Columns: []
# Index: [0, 1, 2]
È possibile specificare più dtype con un elenco. datetime64[ns] può essere specificato con ‘datetime’.
print(df.select_dtypes(include=[float, bool, 'datetime']))
# b e f
# 0 0.1 True 2018-01-01
# 1 0.2 True 2018-02-01
# 2 0.3 False 2018-03-01
I tipi numerici come int e float possono essere specificati insieme a ‘number’.
print(df.select_dtypes(include='number'))
# a b
# 0 1 0.1
# 1 2 0.2
# 2 3 0.3
Poiché il dtype di una colonna i cui elementi sono str è oggetto, viene generato un errore se viene specificato str o ‘str’.
# print(df.select_dtypes(include=str))
# TypeError: string dtypes are not allowed, use 'object' instead
Anche il dtype di una colonna i cui elementi sono tipi predefiniti standard di Python come list e dict è oggetto. Si noti che se si specifica l’oggetto, vengono selezionate anche quelle colonne.
print(df.select_dtypes(include=object))
# c d
# 0 X [0, 0]
# 1 Y [1, 1]
# 2 Z [2, 2]
print(type(df.at[0, 'c']))
# <class 'str'>
print(type(df.at[0, 'd']))
# <class 'list'>
Potrebbe non essere necessario preoccuparsene troppo perché è probabile che oggetti diversi da str non siano elementi di pandas.DataFrame a meno che non lo si gestisca intenzionalmente.
Specificare il tipo da eseguire:exclude
Specificare il dtype da comprendere con il parametro escludere.
È possibile specificare più dtype con un elenco.
print(df.select_dtypes(exclude='number'))
# c d e f
# 0 X [0, 0] True 2018-01-01
# 1 Y [1, 1] True 2018-02-01
# 2 Z [2, 2] False 2018-03-01
print(df.select_dtypes(exclude=[bool, 'datetime']))
# a b c d
# 0 1 0.1 X [0, 0]
# 1 2 0.2 Y [1, 1]
# 2 3 0.3 Z [2, 2]
include ed escludere possono essere specificati contemporaneamente, ma viene generato un errore se viene specificato lo stesso tipo per entrambi.
print(df.select_dtypes(include='number', exclude=int))
# b
# 0 0.1
# 1 0.2
# 2 0.3
# print(df.select_dtypes(include=[int, bool], exclude=int))
# ValueError: include and exclude overlap on frozenset({<class 'numpy.int64'>})
