
- 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 - Cast datatype of only a single column in a Pandas DataFrame
To cast only a single column, use the astype() method. Let us first create a DataFrame with 2 columns. One of them is a “float64” type and another “int64” −
dataFrame = pd.DataFrame( { "Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000], "Units": [90, 120, 100, 150, 200, 130] } )
Check the types −
dataFrame.dtypes
Let’s say we need to cast only a single column “Units” from int64 to int32. For that, use astype() −
dataFrame.astype({'Units': '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 only a single column to int32..." print"\nUpdated DataFrame Types ...\n",dataFrame.astype({'Units': '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 only a single column to int32... Updated DataFrame Types ... Reg_Price float64 Units int32 dtype: object
- Related Articles
- Python - Convert one datatype to another in a Pandas DataFrame
- Pandas series Vs. single-column DataFrame
- Python – Create a new column in a Pandas dataframe
- Python - Sum only specific rows of a Pandas Dataframe
- Write a program in Python to covert the datatype of a particular column in a dataframe
- Python - Calculate the variance of a column in a Pandas DataFrame
- Python – Center align column headers of a Pandas DataFrame
- Python Pandas – Get the datatype and DataFrame columns information
- Python - Stacking a multi-level column in a Pandas DataFrame
- Python - Add a zero column to Pandas DataFrame
- Python - Calculate the standard deviation of a column in a Pandas DataFrame
- Apply uppercase to a column in Pandas dataframe in Python
- Python - Add a prefix to column names in a Pandas DataFrame
- Python Pandas – Display all the column names in a DataFrame
- Python Pandas – Remove numbers from string in a DataFrame column

Advertisements