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

In order to Convert character column to numeric in pandas python we will be using to_numeric() function. astype() function converts or Typecasts string column to integer column in pandas. Let’s see how to

  • Typecast or convert character column to numeric in pandas python with to_numeric() function
  • Typecast character column to numeric column in pandas python with astype() function
  • Typecast or convert string column to integer column in pandas using apply() function.

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

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

 

 

Converting character column to numeric in pandas python: Method 1

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

 

Typecast character column to numeric in pandas python using astype(): Method 2

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

import numpy as np
import pandas as pd

df1['is_promoted'] = df1.is_promoted.astype(np.int64) 
df1.dtypes

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

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

 

Typecast character column to numeric in pandas python using apply(): Method 3

apply() function takes “int” as argument and  converts character column (is_promoted) to numeric column as shown below

import numpy as np
import pandas as pd

df1['is_promoted'] = df1['is_promoted'].apply(int)
df1.dtypes

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

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


 

Other Related Topics:

for further details on to_numeric() function one can refer this documentation.

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

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts