python pandas dataframe columns convert to dict key and value
Solution 1:
If lakes
is your DataFrame
, you can do something like
area_dict = dict(zip(lakes.area, lakes.count))
Solution 2:
With pandas it can be done as:
If lakes is your DataFrame:
area_dict = lakes.to_dict('records')
Solution 3:
You can also do this if you want to play around with pandas. However, I like punchagan's 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}
Solution 4:
If 'lakes' is your DataFrame, you can also do something like:
# Your dataframe
lakes = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'],
'area': [10, 20, 30, 40],
'count': [7, 5, 2, 3]})
lakes.set_index('co tp', inplace=True)
My solution:
area_dict = lakes.set_index("area")["count"].to_dict()
or @punchagan 's solution (which I prefer)
area_dict = dict(zip(lakes.area, lakes.count))
Both should work.
Solution 5:
Answering @Jessie Marks question, on how to use this dict(zip(***)) approach if you want to use multiple columns as keys / values, the answer is to zip the zips; e.g.:
dict(zip(df['key'], zip(df["value col 1"], df_['value col 1'])))
or if you wish to use multiple columns as keys:
dict(zip(zip(df['key 1'], df['key 2']), zip(df["value col 1"], df_['value col 1'])))
this worked for me on pandas v1.1.5 ; python 3.6.13
PS. sorry i do not respond directly under @Jessie Marks question, its new account and I cannot do that yet.