Appearance
Change column type in pandas
In pandas, you can change the data type of a column using the astype() function. You can pass a dictionary to the astype() function where the keys are the column names and the values are the new data types.
For example, if you have a DataFrame called df and you want to change the data type of the column "A" to float, you would do the following:
Change a column's type in a Pandas DataFrame using the astype method in Python
python
df["A"] = df["A"].astype(float)
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
You can also change the data type of multiple columns at once by passing a dictionary to the astype() function. For example:
Change multiple columns' types in a Pandas DataFrame using the astype method in Python
python
df = df.astype({"A": float, "B": int, "C": str})If you want to change the data type of a particular column and also want to change the values of that column in case of error during conversion, you can use the pd.to_numeric and errors='coerce'
Change the data type of a Pandas DataFrame and also change the values of that column in case of error in Python
python
df['A'] = pd.to_numeric(df['A'], errors='coerce')You can also use the pd.to_datetime to change datetime type of column.
Using pd.to_datetime method to change datetime type of a column in Python
python
df['date'] = pd.to_datetime(df['date'])Please make sure the operation suits your needs and won't cause any unexpected values or data loss.