Let us go exploring.
Function Syntax
The function syntax is as illustrated below:
The function parameters are as shown:
- dtype – specifies the target data type to which the Pandas object is cast. You can also provide a dictionary with the data type of each target column.
- copy – specifies if the operation is performed in-place, i.e., affects the original DataFrame or creating a copy.
- errors – sets the errors to either ‘raise’ or ‘ignore.’
Return Value
The function returns a DataFrame with the specified object converted to the target data type.
Example
Take a look at the example code shown below:
import pandas as pd
df = pd.DataFrame({
'col1': [10,20,30,40,50],
'col2': [60,70,80,90,100],
'col3': [110,120,130,140,150]},
index=[1,2,3,4,5]
)
df
Convert Int to Float
To convert the ‘col1’ to floating-point values, we can do:
The code above should convert ‘col1’ to floats as shown in the output below:
Convert to Multiple Types
We can also convert multiple columns to different data types. For example, we convert ‘col1’ to float64 and ‘col2’ to string in the code below.
df = df.astype({
'col1': 'float64',
'col2': 'string'
})
print(f"after: {df.dtypes}")
In the code above, we pass the column and the target data type as a dictionary.
The resulting types are as shown:
Convert DataFrame to String
To convert the entire DataFrame to string type, we can do the following:
The above should cast the entire DataFrame into string types.
Conclusion
In this article, we covered how to convert a Pandas column from one data type to another. We also covered how to convert an entire DataFrame into string type.
Happy coding!!