Is there any possible way to convert pandas Dataframe to dict with list for each row?
Open High Low Close
2021-12-15 12:30:00 1.9000 1.91 1.86 1.8850
2021-12-15 13:30:00 1.8881 1.95 1.88 1.9400
2021-12-15 14:30:00 1.9350 1.95 1.86 1.8956
The output I want
{x:2021-12-15 12:30:00, y:[1.9000,1.91,1.86,1.8850]}
{x:2021-12-15 13:30:00, y:[1.8881,1.95,1.88,1.9400]}
{x:2021-12-15 14:30:00, y:[1.9350,1.95,1.86,1.8956]}
>Solution :
You can use:
dictt=list(zip(df.index,df[['Open','High','Low','Close']].values.tolist()))
final =[{'x':i[0], 'y':i[1]} for i in dictt]
or without loop:
df['y']=df[['Open','High','Low','Close']].values.tolist()
final = df.reset_index(names='x')[['x','combine_col']].to_dict('records')
Output:
[
{
"x":"2021-12-15 12:30:00",
"y":[
1.9,
1.91,
1.86,
1.885
]
},
{
"x":"2021-12-15 13:30:00",
"y":[
1.8881,
1.95,
1.88,
1.94
]
},
{
"x":"2021-12-15 14:30:00",
"y":[
1.935,
1.95,
1.86,
1.8956
]
}
]