Convert pandas df to dict of list

Question:

here
I want to convert a dataframe to dict of list.

Here’s my dataframe

    day     session     sales
0   Friday  Early Morning   11105.50
1   Friday  Evening     8168.00
2   Friday  Late Night  1450.00
3   Friday  Morning     14802.00
4   Friday  Night   2925.00
5   Friday  Noon    10276.25
6   Monday  Early Morning   9553.75
7   Monday  Evening     11431.00

and here’s what i want it to be like, for each and every day and session

monday = {
        "name": "Monday",
        "data": [
            {
                "x": "Morning",
                "y": 18014.00
            }, 
            {
                "x": 'Night',
                "y": 2353.50
            }, 

            }
        ]
}

Thanks

Asked By: Vijayaraghavan

||

Answers:

I suggest to create dictionary for all days for possible select by keys:

df = df.rename(columns={'session':'x', 'sales':'y'})
df1 = df.groupby('day')['x','y'].apply(lambda x: x.to_dict('r')).reset_index(name='data')
print (df1)
      day                                               data
0  Friday  [{'x': 'Early Morning', 'y': 11105.5}, {'x': '...
1  Monday  [{'x': 'Early Morning', 'y': 9553.75}, {'x': '...

d = {k:v.to_dict('r') for k, v in df1.groupby('day')}
#print (d)

print (d['Monday'])
[{'day': 'Monday', 'data': [{'x': 'Early Morning', 'y': 9553.75}, 
                            {'x': 'Evening', 'y': 11431.0}]}]
Answered By: jezrael
def function1(dd:pd.DataFrame):
    return dd.iloc[:,1:].set_axis(["x","y"],axis=1).to_dict("record")

df1.groupby('day').apply(function1).reset_index().set_axis(["name","data"],axis=1).to_dict("record")

output is

[{'name': 'Friday',
  'data': [{'x': 'Early Morning', 'y': 11105.5},
   {'x': 'Evening', 'y': 8168.0},
   {'x': 'Late Night', 'y': 1450.0},
   {'x': 'Morning', 'y': 14802.0},
   {'x': 'Night', 'y': 2925.0},
   {'x': 'Noon', 'y': 10276.25}]},
 {'name': 'Monday',
  'data': [{'x': 'Early Morning', 'y': 9553.75},
   {'x': 'Evening', 'y': 11431.0}]}]
Answered By: G.G
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.