How to Return Pandas DataFrame dtypes as a Dictionary

Using a dictionary to set the data types for a Pandas DataFrame gives you greater control over the schema.

Here is how to return a dictionary of all the columns and respective data types in Pandas:

df.dtypes.apply(lambda x: x.name).to_dict()

Copy and paste what you get as a result into another cell and you can change the data types. Once you are done, you can then apply the new data types back to the original DataFrame:

dtypes_dict = {
  'name':'str',
  'date': 'datetime64[ns]',
  'number': 'int64'
}

df = df.astype(dtypes_dict)

Final Thoughts

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

Thanks for reading!


Posted

in

by

Tags: