Python | Pandas Index.astype()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas Index.astype() function create an Index with values cast to dtypes. The class of a new Index is determined by dtype. When conversion is impossible, a ValueError exception is raised.

Syntax: Index.astype(dtype, copy=True)



Parameters :
dtype : numpy dtype or pandas type
copy : By default, astype always returns a newly allocated object. If copy is set to False and internal requirements on dtype are satisfied, the original data is used to create a new Index or the original Index is returned.

Example #1: Use Index.astype() function to change the data type of index from float to integer type.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd
import pandas as pd
   
# Creating the Index
df=pd.Index([17.3, 69.221, 33.1, 15.5, 19.3, 74.8, 10, 5.5])
  
print("Dtype before applying function: \n", df)
  
print("\nAfter applying astype function:")
# Convert df datatype to 'int64'
df.astype('int64')

chevron_right


Output :

 

Example #2: Use Index.astype() function to change the datatype of the given Index to string form.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd
import pandas as pd
   
# Creating the Index
df=pd.Index([17.3, 69.221, 33.1, 15.5, 19.3, 74.8, 10, 5.5])
  
print("Dtype before applying function: \n", df)
  
print("\nAfter applying astype function:")
# Convert df datatype to 'int64'
df.astype('str')

chevron_right


Output :

 
Example #3: Let’s do something interesting with index.astype() method.

Observe this DataFrame.

Setting ‘Number’ column as index.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas module  
import pandas as pd 
    
# reading csv file from url  
     
# dropping null value columns to avoid errors 
data.dropna(inplace = True
  
# Setting Number column as index
data = data.set_index('Number')
  
# Setting index as None
data.index.names = [None]
data.head(5)

chevron_right


Output:

Now, let’s convert the index to integer.

filter_none

edit
close

play_arrow

link
brightness_4
code

# applying astype on index
data.index.astype('int64')

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.