How to Convert float64 Columns to int64 in Pandas?
float64 represents a floating-point number with double precision and int64 represents a 64-bit integer number. In this article, we will learn to Convert float64 Columns to int64 in Pandas using different methods
Convert float64 Columns to int64 in Pandas DataFrame
To transform a Pandas column to an integer type within a DataFrame, you have the option to utilize either the DataFrame’s astype(int) or the apply() method. This enables the conversion of a column from various data types such as float or string to an integer type, specifically int64 or int32.
1. Using astype() Method
We can use astype() method in Python to convert float64 Columns to int64 in Pandas.
In this example, we create a data frame with floating values and then we convert floating values into integer values using astype() function, This function converts the datatype to another datatype.
Python3
import pandas as pd # Create a sample DataFrame data = { 'A' : [ 1.0 , 2.0 , 3.0 ], 'B' : [ 4.0 , 5.0 , 6.0 ]} df = pd.DataFrame(data) print ( "Before converting" ) print (df.dtypes) # Convert float64 columns to int64 using astype() df[ 'A' ] = df[ 'A' ].astype( 'int64' ) df[ 'B' ] = df[ 'B' ].astype( 'int64' ) print ( "\nAfter converting" ) # Check the data types of columns print (df.dtypes) |
Output:
Before converting
A float64
B float64
dtype: object
After converting
A int64
B int64
dtype: object
As you can observe the float64 values in the dataset are converted to int64 datatype.
2. Using apply() and astype() function
We can use the apply()
method along with the astype(int)
function to convert the columns of the Pandas DataFrame to integers.
Python3
import pandas as pd data = { 'A' : [ 1.0 , 2.4 , 3.0 ], 'B' : [ 4.0 , 5.0 , 6.5 ]} print ( "Before converting" ) print (df.dtypes) # Use apply method to convert Pandas columns to int df_int = df. apply ( lambda column: column.astype( int )) # Check the data types of columns print ( "\nAfter converting" ) print (df_int.dtypes) |
Output:
Before converting
A float64
B float64
dtype: object
After converting
A int64
B int64
dtype: object
As you can observe the float64 values in the dataset are converted to int64 datatype.
Conclusion
In conclusion,we can Convert float64 Columns to int64 in Pandas within few clicks.