Converting numeric column to character in pandas python is accomplished using astype() function. astype() function converts or Typecasts integer column to string column in pandas. Let’s see how to
- Typecast or convert numeric column to character in pandas python with astype() function.
- Typecast or convert numeric to character in pandas python with 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.
Typecast numeric to character column in pandas python:
astype() function converts numeric column (is_promoted) to character column as shown below
# Get current data type of columns df1['is_promoted'] = df1.is_promoted.astype(str) df1.dtypes
“is_promoted” column is converted from numeric(integer) to character (object).
Typecast numeric to character column in pandas python using apply():
apply() function takes “str” as argument and converts numeric column (is_promoted) to character column as shown below
# Get current data type of columns df1['is_promoted'] = df1['is_promoted'].apply(str) df1.dtypes
“is_promoted” column is converted from numeric(integer) to character (object) using apply() function
Other Related Topics:
- Get the data type of column in pandas python
- Convert column to categorical in pandas python
- Convert character column to numeric in pandas python (string to integer)
- 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
- Check and Count Missing values in pandas python
for further details on astype() function one can refer this documentation.