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 astype()

Creating a DataFrame

Let's first create a DataFrame with two columns having different data types ?

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

To cast only the "Units" column from int64 to int32, use 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

You can also use bracket notation to cast a single column ?

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

Use astype() with a dictionary to cast specific columns without affecting others. This method is memory-efficient and allows precise control over DataFrame column types.

Updated on: 2026-03-26T02:25:11+05:30

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements