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
Selected Reading
Python - Convert one datatype to another in a Pandas DataFrame
Use the astype() method in Pandas to convert one datatype to another in a DataFrame. This method allows you to convert columns to specific data types for memory optimization or compatibility requirements.
Creating a DataFrame with Mixed Data Types
Let's create a DataFrame with different column types ?
import pandas as pd
# Create DataFrame with mixed types
dataFrame = pd.DataFrame({
"Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
"Units": [90, 120, 100, 150, 200, 130]
})
print("DataFrame:")
print(dataFrame)
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
Checking Current Data Types
Use the dtypes attribute to view column data types ?
import pandas as pd
dataFrame = pd.DataFrame({
"Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
"Units": [90, 120, 100, 150, 200, 130]
})
print("Original data types:")
print(dataFrame.dtypes)
Original data types: Reg_Price float64 Units int64 dtype: object
Converting All Columns to Same Type
Convert all columns to int32 using astype() ?
import pandas as pd
dataFrame = pd.DataFrame({
"Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
"Units": [90, 120, 100, 150, 200, 130]
})
# Convert all columns to int32
converted_df = dataFrame.astype('int32')
print("After conversion to int32:")
print(converted_df.dtypes)
print("\nConverted DataFrame:")
print(converted_df)
After conversion to int32: Reg_Price int32 Units int32 dtype: object Converted DataFrame: Reg_Price Units 0 7000 90 1 1500 120 2 5000 100 3 8000 150 4 9000 200 5 6000 130
Converting Specific Columns
You can also convert specific columns to different types ?
import pandas as pd
dataFrame = pd.DataFrame({
"Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
"Units": [90, 120, 100, 150, 200, 130]
})
# Convert specific columns to different types
dataFrame['Reg_Price'] = dataFrame['Reg_Price'].astype('int64')
dataFrame['Units'] = dataFrame['Units'].astype('float32')
print("After selective conversion:")
print(dataFrame.dtypes)
print("\nDataFrame:")
print(dataFrame)
After selective conversion: Reg_Price int64 Units float32 dtype: object DataFrame: Reg_Price Units 0 7000 90.0 1 1500 120.0 2 5000 100.0 3 8000 150.0 4 9000 200.0 5 6000 130.0
Conclusion
The astype() method is essential for data type conversion in Pandas. Use it to optimize memory usage, ensure compatibility, or prepare data for specific operations. Remember that converting float to int truncates decimal values.
Advertisements
