Pandas astype()
— one of the most important methods. Used to change the data type of a series. When a data frame is created from a CSV file, the columns are imported and the data type is automatically set, which is often not the case. For example, a salary column can be imported as a string, but in order to perform operations, we must convert it to a float.
astype()
is used for such data type conversions.
Syntax: DataFrame.astype (dtype, copy = True, errors = ’raise’)
Parameters:
dtype: Data type to convert the series into. (for example str, float, int)
copy: Makes a copy of dataframe / series.
errors: Error raising on conversion to invalid data type. For example dict to string. ’raise’ will raise the error and ’ignore’ will pass without raising error.Return type: Series with changed data types
To download the dataset used in the following example, click here.
In the following examples, the data frame used contains the data of some NBA players. An image of the data frame before any operations is attached below.
Example:
In this example, the data frame is imported and .dtypes is called on the dataframe to view the data types of the series. After that, some columns are converted using the .astype () method and the dtypes are scanned again to see the changes.
|
Output:
As shown in the output image , the data types of the columns have been converted accordingly. in the usual way.