Whole-DataFrame type normalization
Normalize every column to a shared numeric or string representation before downstream processing.
Pandas · Module
DataFrame.astype casts an entire DataFrame to one dtype or applies dtypes column by column through a mapping. Invalid conversions raise by default, with errors='ignore' available to suppress them.
Call astype with one dtype to convert the whole DataFrame, or pass a column-to-dtype mapping for selective conversion. The method returns a DataFrame with the requested types; invalid conversions raise by default unless errors is set to ignore.
DataFrame.astype(dtype, copy=<no_default>, errors='raise')| Name | Type | Description |
|---|---|---|
dtype | str, data type, Series, or Mapping of column name to data type | Target dtype for the entire object, or a mapping of column names to individual target dtypes. Supported dtype forms include strings, numpy dtypes, pandas extension dtypes, Python types, and Series. |
copy | bool or no_default | Whether to copy data when performing the conversion. The current documentation signature uses a no-default sentinel. |
errors | {'raise', 'ignore'}, default 'raise' | Controls exception handling for invalid data: raise exceptions or suppress them. |
DataFrame
import pandas as pd
df = pd.DataFrame({"count": [1, 2], "score": [3, 4]})
converted = df.astype({"count": "int32", "score": "float32"})
print(converted.dtypes)A mapping applies a separate target dtype to each named column.
Normalize every column to a shared numeric or string representation before downstream processing.
Convert selected columns to different numeric widths or other target dtypes while preserving unmapped columns.
Attempt a best-effort conversion in a pipeline where invalid values should not immediately abort processing.
Pass a single dtype such as 'int32' to cast the entire DataFrame, or pass a mapping from column labels to dtypes to cast selected columns independently. The mapping can target one or more columns.
Follow-up: How can failed conversions be suppressed? Set errors='ignore'; the documentation defines this option as suppressing exceptions for invalid data.
dtype accepts a string, numpy dtype, pandas extension dtype, Python type, Series, or a mapping of column names to target dtypes. A mapping is useful when columns need different representations.
Follow-up: What happens to unmapped columns? They remain unchanged, so the mapping need not mention every column.
The method returns a DataFrame containing the converted data. By default, errors='raise', so invalid data for the requested dtype produces an exception rather than silently proceeding.
Follow-up: When might errors='ignore' be useful? It can let a pipeline continue when conversion is opportunistic, though callers should verify the resulting dtypes.
pandas.DataFrame.convert_dtypespandas.DataFrame.dtypespandas.Series.astype