简体   繁体   中英

Creating a dictionary by iterating a data frame in pandas row by row

This is one simple dataframe .

sample=pd.DataFrame({'Budjet_id':['K1','K2','K3'],'cost':[20000,30000,4000]})
sample 
   Budjet_id    cost
0       K1     20000
1       K2     30000
2       K3     4000

Convert this into dictionary and embed this in another dictionary like this.

 data={}
 data['work'] = 'Budget'
 data['data_sample']=[{m:sample.values[i][n] for n, m in enumerate(sample.columns)} for i in range(0,len(sample))]
 data

This gives the following output.

{'work': 'Budget',
 'data_sample': [{'Budjet_id': 'K1', 'cost': 20000},
                 {'Budjet_id': 'K2', 'cost': 30000},
                 {'Budjet_id': 'K3', 'cost': 4000}]}

But the expected output is the following.

{'work': 'Budget','data_sample':{'Budjet_id':'K1','cost':'20000'},
               'data_sample':{'Budjet_id':'K2','cost':'30000'},
                'data_sample':{'Budjet_id':'K2','cost':'4000'}}

Is there a way to reach this?

{'work': 'Budget','data_sample':{'Budjet_id':'K1','cost':'20000'},
           'data_sample':{'Budjet_id':'K2','cost':'30000'},
            'data_sample':{'Budjet_id':'K2','cost':'4000'}}

If this is the output that you want it is not a valid dictionary because you have multiple data for the same key.

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