简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM