Change data type for one or more columns in Pandas Dataframe

Method # 1: Using

# import pandas as pd

import pandas as pd

 
# sample data frame

df = pd.DataFrame ({

`A` : [ 1 , 2 , 3 , 4 , 5 ],

`B` : [ `a` , `b` , ` c` , `d` , ` e` ],

`C` : [ 1.1 , `1.0` , `1.3` , 2 5 ]})

 
# convert all columns to string

df = df.astype ( str )

print (df.dtypes)

Output:

# import pandas as pd

import pandas as pd

 
# sample data frame

df = pd.DataFrame ({

  ` A` : [ 1 , 2 , 3 , 4 , 5 ],

`B` : [ `a` , ` b` , `c` , ` d` , `e` ],

`C` : [ 1.1 , `1.0` , ` 1.3` , 2 , 5 ]})

 
# using a dictionary to convert specific columns

convert_dict = { `A` : int ,

`C` : float

}

  

df = df.astype ( convert_dict)

print (df.dtypes)

Output:

Method # 2: Using

# import pandas as pd

import pandas as pd

  
# sample data frame

df = pd.DataFrame ({

  ` A` : [ 1 , 2 , 3 , `4` , `5` ],

  ` B` : [ `a` , `b` , ` c` , `d` , ` e` ],

`C` : [ < code class = "value"> 1.1 , `2.1` , 3.0 , `4.1` , ` 5.1` ]})

 
# using the apply method

df [[ `A` , ` C` ]] = df [[ `A` , `C` ]]. apply (pd.to_numeric)

print (df.dtypes)

Output:

Method # 3: Using DataFrame.infer_objects ()
This method attempts to gently convert by inferring the data type of the object type columns. Non-object and non-reversible columns remain unchanged.

# import pandas as pd

import pandas as pd

 
# sample data frame

df = pd.DataFrame ({

`A` : [ 1 , 2 , 3 , 4 , 5 ],

`B` : [ ` a` , `b` , `c` , `d` , ` e` ],

`C` : [ 1.1 , 2.1 , 3.0 , 4.1 , 5.1 ]

}, dtype = `object` )

 
# data type conversion х

df = df.infer_objects ( )

print (df.dtypes)

Output: