By the end of this tutorial, you will understand how to use the astype() function in Pandas. This function allows you to cast an object to a specific data type.
Let us go exploring.
Function Syntax
The function syntax is as illustrated below:
DataFrame.astype(dtype, copy=True, errors=‘raise’)
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
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:
df.col1.astype(‘float64’, copy=True)
The code above should convert ‘col1’ to floats as shown in the output below:
<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/05/echo/Pandas-Column-Type-String-01.png" data-lazy- height="238" src="data:image/svg xml,” width=”496″>
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.
print(f“before: {df.dtypes}n“)
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:
<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/05/echo/Pandas-Column-Type-String-02.png" data-lazy- height="344" src="data:image/svg xml,” width=”418″>
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!!
About the author
<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/05/echo/john-150×150.png6293eafdebbfd.jpg" height="112" src="data:image/svg xml,” width=”112″>
John Otieno
My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list