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.
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)
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.
Example #2: Use
Index.astype() function to change the datatype of the given Index to string form.
Example #3: Let’s do something interesting with
Observe this DataFrame.
Setting ‘Number’ column as index.
Now, let’s convert the index to integer.