Change a column’s data type in pandas
Convert pandas columns with astype, handle invalid values with to_numeric and to_datetime, and preserve missing values with nullable dtypes.
Use astype() when values are already compatible with the target type. Assign the result back to the column. For text that may contain invalid numbers, use pd.to_numeric(..., errors="coerce") and inspect the newly missing values.
Convert one or several columns
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4.0, 5.0, 6.0]})
df['A'] = df['A'].astype(float)
df['B'] = df['B'].astype(int)
df['A'] = df['A'].astype('string')
# Different target types for different columns
df = df.astype({'A': float, 'B': 'category'})
# Apply the same conversion to selected existing columns
for col in ['A', 'B']:
df[col] = df[col].astype(float)
Targets include int, float, bool, str, NumPy types such as 'int32', and pandas types such as 'Int64', 'string', and 'category'. Converting nonempty text to bool does not parse words: even 'False' is truthy. Map known textual values explicitly instead.
Handle invalid numbers and dates
raw = pd.Series(['12.50', '', 'N/A', '7'])
price = pd.to_numeric(raw, errors='coerce')
invalid = raw.notna() & price.isna()
print(raw[invalid])
created_at = pd.to_datetime(
pd.Series(['2026-10-15', 'invalid']), errors='coerce'
)
Failed numeric conversions become missing values; failed dates become NaT. With errors='raise', parsing fails instead. pandas 3.x does not accept errors='ignore' for these two parsing functions; astype has a separate error-handling contract. Review rejected values before filling or dropping them.
Inspect and infer types
print(df.dtypes)
nullable = df.convert_dtypes()
inferred = df.infer_objects()
convert_dtypes() chooses suitable nullable types; infer_objects() makes more conservative inferences for object columns. Both return a result to assign when needed. At ingestion, you can specify dtype={'id': str} and parse_dates=['created_at'] in pd.read_csv().
FAQ
Why does converting a float column to int fail?
Ordinary integer dtypes cannot hold missing values. Use astype('Int64') for nullable integers, or fill missing values only when the replacement makes sense. Fractional values still need an explicit rounding or truncation policy before conversion to nullable integers.
How do I normalize mixed strings and numbers?
Use pd.to_numeric(column, errors='coerce'), inspect failures, then decide whether to fill or filter them. astype() alone does not clean malformed input.
Why did the conversion not change my DataFrame?
An expression such as df[['A']].astype(float) returns a result; it does not assign that result into df. Use df['A'] = df['A'].astype(float).
Why did memory usage stay the same?
Compare df.memory_usage(deep=True) before and after. An int32 array uses half the element storage of int64, provided its smaller range is sufficient. Categoricals often help repeated strings, but can cost more for high-cardinality data. For strings with missing values, prefer explicit 'string' semantics: pandas 2.x astype(str) can turn missing values into text, whereas pandas 3.x string behavior preserves them.
These examples illustrate the documented APIs; validate conversions against your actual schema and pandas version.
Related reading
- Can one DNS name have multiple CNAME records? (Chinese)
- Copy an SSH public key to the clipboard (Chinese)
See DataFrame.astype reference, pandas.to_numeric reference, pandas.to_datetime reference, pandas 3 string migration guide.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan