Home > OS >  How to convert duplicate column names python dataframe to json
How to convert duplicate column names python dataframe to json

Time:01-04

How to convert dataframe to json

df:

     Name     City   Email          City 
     Andrew   Tokyo  [email protected]   Sydney

Required format

json_required = {'Name': 'Andrew',
'City': 'Tokyo',
'Email': '[email protected]',
'City': 'Sydney'}

CodePudding user response:

Since dictionaries can't have duplicate keys, one way is to create a list of items for those who were about to be in duplicate keys. The below solution will create a list of dictionaries. This could be useful if you have a dataframe with more than 1 row.

out = df.groupby(df.columns, axis=1).agg(lambda x: x.to_numpy().tolist() if x.shape[1]>1 else x.to_numpy().flatten()).to_dict('records')

Output:

[{'City': ['Tokyo', 'Sydney'], 'Email': '[email protected]', 'Name': 'Andrew'}]
  •  Tags:  
  • Related