Index.astype()
Pandas Index.astype()
crea un indice con valori cast to dtypes ... La classe del nuovo indice è determinata dal dtype. Quando la conversione non è possibile, viene generato un ValueError.
Sintassi: Index.astype (dtype, copy = True)
Parametri:
dtype: numpy dtype o pandas type
copy: Per impostazione predefinita, astype restituisce sempre un oggetto appena allocato. Se copy è impostato su False e i requisiti interni su dtype sono soddisfatti, i dati originali vengono utilizzati per creare un nuovo Indice o viene restituito l’Indice originale.
Esempio n. 1: Usa Index.astype ()
per cambiare il tipo di dati di un indice da mobile a intero.
< td class = "codice"> # importa panda come pd
import
panda come pd
# Crea indice
df
=
pd.Index ([
17.3
, 69.221 , 33.1 , 15.5 , 19.3 , 74.8 , 10 , 5.5 ] )
print ( "Dtype prima di applicare la funzione:" , df)
print
(
"Dopo aver applicato la funzione astype:"
)
# Converti il tipo di dati df in int64
df.astype (
’int64’
)
Output:
< p>
Esempio n. 2: utilizza
Index.astype ()
per modificare il tipo di dati di questo indice in formato stringa.
# importa panda come pd importa panda come pd # Crea indice df = pd.Index ([ 17.3 , 69.221 , 33.1 , 15.5 , 19.3 , 74.8 , 10 , 5.5 ]) print ( "Dtype prima di applicare la funzione:" , df) print ( "Dopo aver applicato la funzione astype:" ) # Converti tipo di dati df in int64 df.astype ( ’str’ ) |
Output:
Esempio n. 3:
strong> Facciamo qualcosa di interessante con index.astype ()
.
Osserva questo DataFrame.
Impostazione della colonna Numero come indice.
# importazione del modulo pandas import panda come pd # leggi il file CSV dall’URL dati = pd.read_csv ( " https://media.python.engineering/wp-content/uploads/nba.csv " ) # rimuovi le colonne null per evitare errori data.drop na (inplace = Vero ) # Impostazione del numero di colonna come indice data = data.set_index ( ’Numero’ ) # Indice di installazione come Nessuno data.index.names = [ Nessuno ] dati. head ( 5 ) |
Output:
Ora convertiamo l’indice in un intero h islo.
# applicazione di astype all’indice data.index.astype ( ’int64’ ) |
Output:
Ci auguriamo che questo articolo ti abbia aiutato a risolvere il problema. Oltre a Python | Pandas Index.astype (), controlla altri argomenti relativi a Python functions.
Vuoi eccellere in Python? Consulta la nostra recensione dei migliori corsi online Python 2023. Se sei interessato alla scienza dei dati, controlla anche come imparare a programmare in R.
A proposito, questo materiale è disponibile anche in altre lingue:
Davies Danburry
Singapore | 2023-01-31
Grazie per le spiegazioni! Sono rimasto bloccato con Python | Pandas Index.astype () per alcune ore, finalmente l'ho fatto 🤗. Lo userò nella mia tesi di laurea
Marie Gonzalez
London | 2023-01-31
Python functions è tutto un po' confuso 😭 Python | Pandas Index.astype () non è l'unico problema che ho riscontrato. Spero solo che non emerga più
Cornwall Robinson
New York | 2023-01-31
Semplice e chiaro. Grazie per la condivisione. Il mio punto debole è sempre stato il Python | Pandas Index.astype () e altri problemi con il Python functions 😁. Non sono proprio sicuro che sia il metodo migliore
Shop
Learn programming in R: courses
$FREE
Best Python online courses for 2022
$FREE
Best laptop for Fortnite
$399+
Best laptop for Excel
$
Best laptop for Solidworks
$399+
Best laptop for Roblox
$399+
Best computer for crypto mining
$499+
Best laptop for Sims 4
$
Latest questions
PythonStackOverflow
Common xlabel/ylabel for matplotlib subplots
1947 answers
PythonStackOverflow
Check if one list is a subset of another in Python
1173 answers
PythonStackOverflow
How to specify multiple return types using type-hints
1002 answers
PythonStackOverflow
Printing words vertically in Python
909 answers
PythonStackOverflow
Python Extract words from a given string
798 answers
PythonStackOverflow
Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?
606 answers
PythonStackOverflow
Python os.path.join () method
384 answers
PythonStackOverflow
Flake8: Ignore specific warning for entire file
360 answers
Wiki
Python | How to copy data from one Excel sheet to another
Common xlabel/ylabel for matplotlib subplots
Check if one list is a subset of another in Python
How to specify multiple return types using type-hints
Printing words vertically in Python
Python Extract words from a given string
Cyclic redundancy check in Python
Finding mean, median, mode in Python without libraries
Python add suffix / add prefix to strings in a list
Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?
Python - Move item to the end of the list
Python - Print list vertically