

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Python - Cast datatype of only a single column in a Pandas DataFrame
- Python - Convert Pandas DataFrame to binary data
- Python Pandas – Get the datatype and DataFrame columns information
- Python Pandas – Merge DataFrame with one-to-one relation
- Python Pandas - Convert Nested Dictionary to Multiindex Dataframe
- Convert a Pandas DataFrame to a NumPy array
- Python - Replace values of a DataFrame with the value of another DataFrame in Pandas
- Python Pandas - Convert Timestamp to another time zone
- 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 add column from another DataFrame in Pandas?
- Python - Convert list of nested dictionary into Pandas Dataframe
- How to select all columns except one in a Pandas DataFrame?
- Write a program in Python Pandas to convert a dataframe Celsius data column into Fahrenheit
Advertisements