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
Datatypes of df1 will be
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).
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).
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).
Other Related Topics:
- Get the data type of column in pandas python
- Check and Count Missing values in pandas python
- Convert column to categorical in pandas python
- Convert numeric column to character in pandas python (integer to string)
- Extract first n characters from left of column in pandas python
- Extract last n characters from right of the column in pandas python
- Replace a substring of a column in pandas python
for further details on to_numeric() function one can refer this documentation.