Pandas DataFrame | astype method
Start your free 7-days trial now!
Pandas DataFrame.astype(~) method converts the data type of the columns of a DataFrame to the specified type.
Parameters
1. dtype | string or type or dict of (string, string or type)
The desired data type to convert the DataFrame to.
2. copy | boolean | optional
Whether or not to return a new DataFrame:
If
True, then a copy is returned - modifying the return value will not mutate the original DataFrame and vice versa.If
False, then a view is returned - modifying the return value will mutate the original DataFrame and vice versa.
By default, copy=True.
3. errorslink | string | optional
How to deal with cases where the type of the data in the source DataFrame cannot be converted to the specified type:
Value | Description |
|---|---|
| Throw an error. |
| Return the source DataFrame in case of errors. |
By default, errors="raise".
Return Value
A DataFrame with the new specified type.
Examples
Consider the following DataFrame:
df
A B0 4 61 5 7
Converting to float
To convert df to type float:
df.astype("float")
A B0 4.0 6.01 5.0 7.0
Note that the original df is still of type int.
Handling errors
Raise
The default behaviour when type conversion fails is to throw an error:
df.astype("int")
ValueError: invalid literal for int() with base 10: 'a'
Ignore
We could suppress the error, and simply get the original DataFrame back:
df.astype("int", errors="ignore")
A0 a1 b