Type Conversion
Converting between data types is essential for proper data analysis. Pandas provides several methods for type conversion.
Checking Data Types
Inspect column types before converting:
Loading Pandas Playground...
Using astype()
Convert columns to specific types:
Loading Pandas Playground...
String to Numeric
Handle string-to-number conversion:
Loading Pandas Playground...
pd.to_numeric()
Safely convert to numbers with error handling:
Loading Pandas Playground...
Boolean Conversion
Convert to boolean type:
Loading Pandas Playground...
Category Type
Convert to categorical for efficiency:
Loading Pandas Playground...
Multiple Column Conversion
Convert multiple columns at once:
Loading Pandas Playground...
Exercise: Convert Strings
Loading Exercise...
Exercise: Safe Numeric Conversion
Loading Exercise...
Key Points
.dtypesshows column types.astype()converts to specified typepd.to_numeric()witherrors='coerce'for safe conversion.map()for custom value mappingcategorytype saves memory for repeated values- Pass dict to
.astype()for multiple columns

