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
-
Economics & Finance
Python - Cast datatype of only a single column in a Pandas DataFrame
In Pandas, you can cast the datatype of only a single column using the Let's first create a DataFrame with two columns having different data types ? To cast only the "Units" column from int64 to int32, use You can also use bracket notation to cast a single column ? Use astype()
Creating a DataFrame
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:")
print(dataFrame)
print("\nDataFrame Types:")
print(dataFrame.dtypes)
DataFrame:
Reg_Price Units
0 7000.5057 90
1 1500.0000 120
2 5000.0000 100
3 8000.0000 150
4 9000.7577 200
5 6000.0000 130
DataFrame Types:
Reg_Price float64
Units int64
dtype: object
Casting a Single Column
astype() with a dictionary ?
import pandas as pd
dataFrame = pd.DataFrame(
{
"Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
"Units": [90, 120, 100, 150, 200, 130]
}
)
# Cast only the Units column to int32
dataFrame_updated = dataFrame.astype({'Units': 'int32'})
print("Original Types:")
print(dataFrame.dtypes)
print("\nUpdated Types:")
print(dataFrame_updated.dtypes)
Original Types:
Reg_Price float64
Units int64
dtype: object
Updated Types:
Reg_Price float64
Units int32
dtype: object
Alternative Methods
import pandas as pd
dataFrame = pd.DataFrame(
{
"Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
"Units": [90, 120, 100, 150, 200, 130]
}
)
# Method 1: Using dictionary with astype()
dataFrame['Units'] = dataFrame['Units'].astype('int32')
# Method 2: Using pd.to_numeric() for numeric conversions
dataFrame['Units'] = pd.to_numeric(dataFrame['Units'], downcast='integer')
print("Final Types:")
print(dataFrame.dtypes)
Final Types:
Reg_Price float64
Units int32
dtype: object
Conclusion
astype() with a dictionary to cast specific columns without affecting others. This method is memory-efficient and allows precise control over DataFrame column types.
