Pandas – astype() – Change column data type in pandas

Spread the love

pandas.DataFrame.astype() –

astype method in pandas helps you change the data type of a column from one type to another. It is one of the most used method for converting data type in pandas.

Let’s see how to use it.

import pandas as pd

df = pd.read_csv("https://raw.githubusercontent.com/bprasad26/lwd/master/data/gapminder.tsv", sep='\t')
df.head()

To check the data types of a columns, we can use the df.dtypes attribute.

df.dtypes

1 . Convert from Integer to Float –

To convert a integer column to float, you will write

df['year'] = df['year'].astype('float')

2 . Convert from Float to Integer –

To convert float column to integer, you have to write

df['lifeExp'] = df['lifeExp'].astype('int')

3 . Convert from Integer or Float to String –

To convert from integer or float to string you have to write

df['lifeExp'] = df['lifeExp'].astype('str')

4 . Convert from string to Integer or Float –

Sometimes a numerical column is represented as a string column and you want to convert it into a integer or float type.

df['lifeExp'] = df['lifeExp'].astype('int')

Rating: 1 out of 5.

Leave a Reply