Pandas DataFrame function astype() in Python
The Pandas DataFrame function astype() used to cast the pandas object to a specified dtype.astype() function. It also convert any suitable existing column to a categorical type. It returns the same type as a caller.
Syntax
 1 DataFrame.astype(dtype, copy = True, errors = 'raise', **kwargs)  
dtype : It specifies the data type for the casting, it can be specified either numpy.dtype or the Python type for entire pandas object to the same type.
copy : It expects a boolean value, if specified value is True, it returns a copy. Otherwise, may propagate to other pandas objects.
errors : If specified, it raises an exceptions on the invalid data.
1. raise : If specified, it will raises an exception on invalid data.2. ignore : If specified, it ignores the exception and return the original object on error.
**kwds : It is an optional keyword argument that used to pass as keywords arguments to function
astype() function
 1 import pandas as pd
 2 import numpy as np
 3 
 4 dict1 = { 'Col1': [1, 2], 'Col2': [3, 4]}
 5 df = pd.DataFrame(dict1)
 6 print('The data type of dataframe is :')
 7 print(df.dtypes)
 8 
 9 df.astype('int64').dtypes
 10 df.astype({'Col1': 'int64'}).dtypes
 11 
 12 print('The data type of dataframe :')
 13 print(df.dtypes)
In the above example, a dictionary object is created with two columns. A dataframe object is created by passing dictionary object. A astype() function is called which will returns an type that will be printed on console.
Output
 1 The data type of dataframe is :
 2 Col1    int64
 3 Col2    int64
 4 dtype: object
 5 The data type of dataframe :
 6 Col1    int64
 7 Col2    int64
 8 dtype: object

Example 2

Example 2
 1 import pandas as pd
 2 import numpy as np
 3 
 4 dict1 = { 'Col1': [5.32, 6.21], 'Col2': [7.324, 2.369]}
 5 df = pd.DataFrame(dict1)
 6 print('The data type of dataframe is :')
 7 print(df.dtypes)
 8 
 9 df.astype('float64').dtypes
 10 df.astype({'Col1': 'float64'}).dtypes
 11 
 12 print('The data type of dataframe :')
 13 print(df.dtypes)
In the above example, a dictionary object is created with two columns. A dataframe object is created by passing dictionary object. A astype() function is called which will returns an type that will be print.
Output
 1 The data type of dataframe is :
 2 Col1    float64
 3 Col2    float64
 4 dtype: object
 5 The data type of dataframe :
 6 Col1    float64
 7 Col2    float64
 8 dtype: object
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us