Home > Software engineering >  creating a list of dictionaries from pandas dataframe
creating a list of dictionaries from pandas dataframe

Time:10-13

This is my df:

df = pd.DataFrame({'sym': ['a', 'b', 'c', 'x', 'y', 'z', 'q', 'w', 'e'],
                   'sym_t': ['tsla', 'msft', 'f', 'aapl', 'aa', 'gg', 'amd', 'ba', 'c']})

I want to separate this df into groups of three and create a list of dictionaries:

options = [{'value':'a b c', 'label':'tsla msft f'}, {'value':'x y z', 'label':'aapl aa gg'}, {'value':'q w e', 'label':'amd ba c'}]

How can I create that list? My original df has over 1000 rows.

CodePudding user response:

Try groupby to concatenate the rows, then to_dict:

tmp = df.groupby(np.arange(len(df))//3).agg(' '.join)
tmp.columns = ['value', 'label']
tmp.to_dict(orient='records')

Output:

[{'value': 'a b c', 'label': 'tsla msft f'},
 {'value': 'x y z', 'label': 'aapl aa gg'},
 {'value': 'q w e', 'label': 'amd ba c'}]
  • Related