Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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
        ]
    }
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading