Home > Software engineering >  DataFrame dtypes to list of dicts
DataFrame dtypes to list of dicts

Time:10-03

I have a very wide dataframe, and I need the dtypes of all the columns as a list of dicts:

[{'name': 'col1', 'type': 'STRING'},...]

I need to do that to supply this as the schema for a BigQuery table.

How could that be achieved? Thank you!

CodePudding user response:

Use a comprehension:

out = [{'name': col, 'type': dtype.name} for col, dtype in df.dtypes.items()]
print(out)

# Output:
[{'name': 'col1', 'type': 'float64'}, {'name': 'col2', 'type': 'float64'}]

CodePudding user response:

You can try :

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