Changing the datatype of columns in pandas dataframe is very easy. Here I am using stype() function to perform the typecase operation. Refer to the following example. The type conversion is happening in the line number 10 of the code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
# create a sample dataframe | |
df = pd.DataFrame({'emp_id': ['111', '112', '113'], 'salary': ['40000', '50000', '60000'], 'name':['amal', 'sabitha', 'edward']}) | |
# print the dataframe | |
print(df) | |
# print the datatypes in the dataframe | |
print(df.dtypes) | |
# now let us convert the data type of salary to integer | |
df = df.astype({'salary':'int'}) | |
# print the dataframe | |
print(df) | |
# print the datatypes in the dataframe | |
print(df.dtypes) |
You can add as many columns as you want to convert the data type or typecast. For example if you want to typecast the columns emp_id and salary, use the following syntax.
> df = df.astype({‘salary’:‘int’, ’emp_id’:’int’})