🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpandas

pandas Documentation

LOADING ENGINE...

df.astype()

AI & DATA SCIENCE // df-astype

df.astype() converts a column's (or the whole DataFrame's) dtype to a specified new type, such as turning text into numbers or numbers into a different numeric precision.

Syntax

df.astype(dtype)

Deep Dive Course

astype() always returns a new DataFrame/Series with the converted type, leaving the original unmodified, and it raises an error if any value can't actually be converted to the target type — trying to convert a column containing a non-numeric string to int, for example, fails with a clear error rather than silently producing garbage. Passing a dict lets you convert multiple columns to different specific types in one call.

1Understanding df.astype()

astype() always returns a new DataFrame/Series with the converted type, leaving the original unmodified, and it raises an error if any value can't actually be converted to the target type — trying to convert a column containing a non-numeric string to int, for example, fails with a clear error rather than silently producing garbage. Passing a dict lets you convert multiple columns to different specific types in one call.

💡

astype() raises an error the moment it hits a value it can't convert — use pd.to_numeric(series, errors='coerce') instead when you specifically want unconvertible values replaced with NaN rather than the whole conversion failing outright.

editor.html
import pandas as pd

df = pd.DataFrame({"id": ["1", "2", "3"]})
df["id"] = df["id"].astype(int)
print(df.dtypes)
localhost:3000

2Practical Example

Here is a real-world application of df.astype() showing how it is used in production Pandas code.

editor.html
import pandas as pd

df = pd.DataFrame({"a": [1, 2], "b": [3.5, 4.5]})
df = df.astype({"a": float, "b": int})
print(df.dtypes)
localhost:3000

3Best Practices

Follow these guidelines when working with df.astype():

1. Use a dict argument to astype() to convert several columns to different specific types in one call, instead of separate astype() calls per column

2. Use pd.to_numeric(..., errors='coerce') instead of astype() when some values might genuinely be unconvertible and should become NaN rather than raise an error

3. Convert numeric columns to a smaller dtype, like int32 or float32, deliberately when memory usage matters for a large DataFrame

⚠️

Tip: astype() raises an error the moment it hits a value it can't convert — use pd.to_numeric(series, errors='coerce') instead when you specifically want unconvertible values replaced with NaN rather than the whole conversion failing outright.

editor.html
import pandas as pd

df = pd.DataFrame({"id": ["1", "2", "3"]})
df["id"] = df["id"].astype(int)
print(df.dtypes)
localhost:3000

Examples

Example 01Basic Usage
import pandas as pd

df = pd.DataFrame({"id": ["1", "2", "3"]})
df["id"] = df["id"].astype(int)
print(df.dtypes)
Example 02Advanced Example
import pandas as pd

df = pd.DataFrame({"a": [1, 2], "b": [3.5, 4.5]})
df = df.astype({"a": float, "b": int})
print(df.dtypes)

Best Practices

  • Use a dict argument to astype() to convert several columns to different specific types in one call, instead of separate astype() calls per column
  • Use pd.to_numeric(..., errors='coerce') instead of astype() when some values might genuinely be unconvertible and should become NaN rather than raise an error
  • Convert numeric columns to a smaller dtype, like int32 or float32, deliberately when memory usage matters for a large DataFrame

Interview Question

What happens if you call astype(int) on a column that contains a non-numeric string mixed in with otherwise valid numeric strings?

Hint: Think about whether astype() tries to guess or silently skip unconvertible values.

astype() raises a ValueError the moment it encounters a value it can't convert to the target type — a non-numeric string isn't a valid integer literal, so the entire conversion fails outright rather than converting the valid values and silently skipping or replacing the invalid one. If you need a conversion that tolerates unconvertible values by turning them into NaN instead of failing the whole operation, you'd use pd.to_numeric(series, errors='coerce') instead, which is specifically designed to handle that more forgiving case.

Exercises

MediumPractice using df.astype() in a real scenario.
View Solution
import pandas as pd

df = pd.DataFrame({"id": ["1", "2", "3"]})
df["id"] = df["id"].astype(int)
print(df.dtypes)

Frequently Asked Questions

What happens if you call astype(int) on a column that contains a non-numeric string mixed in with otherwise valid numeric strings?

astype() raises a ValueError the moment it encounters a value it can't convert to the target type — a non-numeric string isn't a valid integer literal, so the entire conversion fails outright rather than converting the valid values and silently skipping or replacing the invalid one. If you need a conversion that tolerates unconvertible values by turning them into NaN instead of failing the whole operation, you'd use pd.to_numeric(series, errors='coerce') instead, which is specifically designed to handle that more forgiving case.

Related Functions

df-dtypespd-to-datetimeint()