
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Convert one datatype to another in a Pandas DataFrame
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
- Related Articles
- Python - Cast datatype of only a single column in a Pandas DataFrame
- Python Pandas – Get the datatype and DataFrame columns information
- Python - Convert Pandas DataFrame to binary data
- How to convert pandas DataFrame into JSON in Python?
- Python Pandas - Convert Nested Dictionary to Multiindex Dataframe
- Python Pandas – Merge DataFrame with one-to-one relation
- Python - Replace values of a DataFrame with the value of another DataFrame in Pandas
- Python Pandas - Convert Timestamp to another time zone
- Convert a Pandas DataFrame to a NumPy array
- Python Pandas – Merge DataFrame with one-to-many relation
- Python Pandas – Merge DataFrame with many-to-one relation
- How to convert a DataFrame into a dictionary in Pandas?
- How to Convert Pandas to PySpark DataFrame?
- Python - Convert list of nested dictionary into Pandas Dataframe
- How to add column from another DataFrame in Pandas?

Advertisements