How to convert Pandas Dataframe to list of dict for each row

Question:

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]}
Asked By: Ujjal Modak

||

Answers:

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().rename(columns={'index':'x'})[['x','y']].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
        ]
    }
]
Answered By: Bushmaster

If you want to convert a dataframe to a list of dict,you simply need to specify orient=’index’ … So in your case if:

df = pd.DataFrame({'o':[1,2,3],'l':[4,5,6],'x':[7,8,9]},index=['t1','t2','t3'])

then you can do:

[{'x':k,'y':list(v.values())} for k,v in df.to_dict(orient='index').items()]

or also:

df2 = pd.DataFrame(df.apply(lambda x:list(x[df.columns]), axis=1))
list(df2.reset_index().rename(columns={'index':'x',0:'y'}).to_dict(orient='index').values())

Either results to:

[{'x': 't1', 'y': [1, 4, 7]},
 {'x': 't2', 'y': [2, 5, 8]},
 {'x': 't3', 'y': [3, 6, 9]}]
Answered By: ntg
df1.apply(lambda ss:ss.tolist(),axis=1).reset_index().set_axis(['x','y'],axis=1)
    .apply(lambda ss:ss.to_dict(),axis=1)

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]}
Answered By: G.G