How to Dynamically Convert Pandas Object Columns to a String Data Type

Since Pandas allows you to have mixed data type columns, converting them to a string data type can be essential when exporting the data.

An object data type can mean that the column is comprised of string values or mixed data type values. That can be troublesome when trying to export the data to a database or when converting the data to a parquet file. To convert Pandas object columns to string columns, you can simply run a for loop on each object column to convert them:

for i in df.select_dtypes(include='object').columns.tolist():
  df[i] = df[i].astype(str)

Final Thoughts

Check out more Python tricks in this Colab Notebook or in my recent Python Posts.

Thanks for reading!


Posted

in

by

Tags: