Python - Convert one datatype to another in a Pandas DataFrame

PythonServer Side ProgrammingProgramming

Use the astype() method in Pandas to convert one datatype to another. Import the required library −

import pandas as pd

Create a DataFrame. Here, we have 2 columns, “Reg_Price” is a float type and “Units” int type −

dataFrame = pd.DataFrame(
   {
      "Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
      "Units": [90, 120, 100, 150, 200, 130]
   }
)

Check the datatypes of the columns created above −

dataFrame.dtypes

Convert both the types to int32 −

dataFrame.astype('int32').dtypes

Example

Following is the code −

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
      "Units": [90, 120, 100, 150, 200, 130]
   }
)

print"DataFrame ...\n",dataFrame
print"\nDataFrame Types ...\n",dataFrame.dtypes
print"\nCast all columns to int32..."

print"\nUpdated DataFrame Types ...\n",dataFrame.astype('int32').dtypes

Output

This will produce the following output −

DataFrame ...
   Reg_Price   Units
0 7000.50570     90
1 1500.00000    120
2 5000.00000    100
3 8000.00000    150
4 9000.75768    200
5 6000.00000    130

DataFrame Types ...
Reg_Price   float64
Units         int64
dtype: object

Cast all columns to int32...

Updated DataFrame Types ...
Reg_Price   int32
Units       int32
dtype: object
raja
Published on 16-Sep-2021 08:55:23
Advertisements