Convert character column to numeric in pandas python (string to integer)

Converting character column to numeric in pandas python is carried out using to_numeric() function. Let’s see how to

  • Typecast or convert character column to numeric in pandas python With an example

First let’s create a dataframe.


import pandas as pd
import numpy as np

#Create a DataFrame
df1 = {
'Name':['George','Andrea','micheal','maggie','Ravi','Xien','Jalpa'],
'is_promoted':['0','1','0','0','1','0','1']}

df1 = pd.DataFrame(df1,columns=['Name','is_promoted'])
print(df1)

df1 will be

Convert character column to numeric in pandas python (string to integer) 1

Datatypes of df1 will be

Convert character column to numeric in pandas python (string to integer) 2

Object datatype of pandas is nothing but character (string) datatype of python

 

Convert character column to numeric in pandas python:

to_numeric() function converts character column (is_promoted) to numeric column as shown below


df1['is_promoted']=pd.to_numeric(df1.is_promoted)
df1.dtypes

“is_promoted” column is converted from character to numeric (integer).

Convert character column to numeric in pandas python (string to integer) 3

Convert character column to numeric in pandas python (string to integer)                                                                                                                Convert character column to numeric in pandas python (string to integer)