Use DataFrame. To convert pandas DataFrame to Dictionary object, use to_dict() method, this takes orient as dict by default which returns the DataFrame in format {column -> {index -> value}} . When no orient is specified, to_dict() returns in this format.
Another approach to convert two column values into a dictionary is to first set the column values we need as keys to be index for the dataframe and then use Pandas' to_dict() function to convert it a dictionary. This creates a dictionary for all columns in the dataframe.
A pandas DataFrame can be converted into a Python dictionary using the DataFrame instance method to_dict(). The output can be specified of various orientations using the parameter orient. In dictionary orientation, for each column of the DataFrame the column value is listed against the row label in a dictionary.
If lakes
is your DataFrame
, you can do something like
area_dict = dict(zip(lakes.area, lakes.count))
With pandas it can be done as:
If lakes is your DataFrame:
area_dict = lakes.to_dict('records')
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}
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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With