• Register

This error usually occurs when the user tries conversion to an invalid data type.

Example:

For example, dict to string “raise” will raise the error, and ‘ignore’ will pass without raising an error.

Pandas Series.astype() to convert Data types of series:

Python is a great language for doing data analysis, 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 astype():

This is one of the most important methods. It is used to change the data types of series. When the data frame is made from a CSV file, the columns are imported and data type is set automatically which many times is not what is actually should have.

Example:

For example, a salary column could be imported as a string but to do operations we have to convert it into the float.

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 the data frame/series.

Errors: 

Error raising on conversion to the invalid data type. For Example, dict to the string. “Raise” will raise the error and ‘ignore’ will pass without raising the error.

Return Type:

 Series with the changed data type.

posted Jul 8 in python 3,890 points