How to Convert String Column to Integer in Pandas

Spread the love

Problem –

You have a numerical column which is represented as string and you want to convert it to Integer type.

Solution –

There are several method for converting a string column to integer in pandas, let’s look at them one by one.

Method 1 – astype() –

Let’s read a dataset to illustrate it.

import pandas as pd
url = ""
df = pd.read_csv(url)

Now, Let’s check the data types of the columns


You can see that the Meal Price column is represented as string (object) type instead of Integer type.

Now, to convert this column to Integer, first we have to remove all the dollar signs from this column.

df['Meal Price'] = df['Meal Price'].str.replace("$","")

Now, we can use the astype method in pandas to do the conversion.

df['Meal Price'] = df['Meal Price'].astype(int)

Method 2 – pd.to_numeric() –

Another method for converting a string column to Integer is the pandas pd.to_numeric()

df['Meal Price'] = pd.to_numeric(df['Meal Price'], errors='coerce')

error=’coerce’ convert any invalid values into NaN ( Not a number ).


1 . How to Convert a String Column to Float in Pandas

Rating: 1 out of 5.

Leave a Reply