Python pandas columns dataframe convert to dict key and value

From a Python pandas data frame with multiple columns, I would like to build a dict from only two columns. One as dict keys, and the other as dict values. How can i do this?

Dataframe:

area count co tp DE Lake 10 7 Forest 20 5 FR Lake 30 2 Forest 40 3 

It is necessary to define the area as a key, count as the value in the dict. Thank you in advance.

+58
python dictionary pandas data-conversion dataframe
Aug 2 '13 at 8:46
source share
3 answers

If lakes is your DataFrame , you can do something like

 area_dict = dict(zip(lakes.area, lakes.count)) 
+139
Aug 2 '13 at 9:42 on
source share

With pandas this can be done like this:

If the lakes are your DataFrame:

 area_dict = lakes.to_dict('records') 
+2
Apr 17 '18 at 7:55
source share

You can also do this if you want to play with pandas. However, I love the Punchagan way.

 # replicating your dataframe lake = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'], 'area': [10, 20, 30, 40], 'count': [7, 5, 2, 3]}) lake.set_index('co tp', inplace=True) # to get key value using pandas area_dict = lake.set_index('area').T.to_dict('records')[0] print(area_dict) output: {10: 7, 20: 5, 30: 2, 40: 3} 
0
Nov 13 '18 at 23:46
source share



All Articles