Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
