json 将Pandasdf转换为list的dict

8yparm6h  于 2023-03-04  发布在  其他
关注(0)|答案(2)|浏览(222)

这里我想把一个 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

这就是我想要的每一天每一节课

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

            }
        ]
}

谢谢

gorkyyrv

gorkyyrv1#

我建议为所有日期创建字典,以供key s选择:

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}]}]
cbeh67ev

cbeh67ev2#

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")

输出为

[{'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}]}]

相关问题