Change Data Type for one or more columns in Pandas Dataframe

PythonServer Side ProgrammingProgrammingPandas

In this tutorial, we are going to learn about the conversion of one or more columns data type into another data type. We are going to use the method DataFrame.astype() method.

We have to pass any data type from Python, Pandas, or Numpy to change the column elements data types. We can also give a dictionary of selected columns to change particular column elements data types. Let's see the examples with code.

Example

# importing the pandas library
import pandas as pd
# creating a DataFrame
data_frame = pd.DataFrame({'No': [1, 2, 3], 'Name': ['Tutorialspoint', 'Mohit', 'Sharma'], 'Age': [25, 32, 21]})
# we will change the data type of all columns to str
data_frame = data_frame.astype(str)
# checking the data types using data_frame.dtypes method
print(data_frame.dtypes)

Output

All the column data types changed to str objects. If you run the above program, you will get the following results.

No     object
Name   object
Age    object
dtype: object

Now, let's try to change the data type of Age column from int to str. We have to create a dictionary specifying column name and desired data type.

Example

# importing the pandas library
import pandas as pd
# creating a DataFrame
data_frame = pd.DataFrame({'No': [1, 2, 3], 'Name': ['Tutorialspoint', 'Mohit', 'Sharma'], 'Age': [25, 32, 21]})
# creating a dictionary with column name and data type
data_types_dict = {'Age': str}
# we will change the data type of Age column to str by giving the dict to the astype method
data_frame = data_frame.astype(data_types_dict)
# checking the data types using data_frame.dtypes method
print(data_frame.dtypes)

Output

If you see the output, only the Age column data type is changed from int to str. See the result below.

No      int64
Name   object
Age    object
dtype: object

Conclusion

If you face any difficulties in following the tutorial, mention them in the comment section.

raja
Published on 02-Jan-2020 10:56:09
Advertisements