Home > OS >  How to convert Pandas Dataframe to list of dict for each row
How to convert Pandas Dataframe to list of dict for each row

Time:12-16

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

CodePudding user response:

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

CodePudding user response:

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:

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

results to:

[{'x': 't1', 'y': [1, 4, 7]},
 {'x': 't2', 'y': [2, 5, 8]},
 {'x': 't3', 'y': [3, 6, 9]}]
  • Related