I have the dataframe
ID A B C
0 p 1 3 2
1 q 4 3 2
2 r 4 0 9
And I want to create a dict where ID is the keys and B is the values so it will be:
d["q"] = 3 , d["r"] = 0
What is the best way to do so?
It is different than the supposed duplicate becasue I want single value per key and not a list
You can use df. to_dict() in order to convert the DataFrame to a dictionary.
To create a dictionary from two column values, we first create a Pandas series with the column for keys as index and the other column as values. And then we can apply Pandas' to_dict() function to get dictionary.
to_dict() method is used to convert a dataframe into a dictionary of series or list like data type depending on orient parameter. Parameters: orient: String value, ('dict', 'list', 'series', 'split', 'records', 'index') Defines which dtype to convert Columns(series into).
Pandas can create dataframes from many kinds of data structures—without you having to write lots of lengthy code. One of those data structures is a dictionary.
Something like this:
In [27]: df
Out[27]:
ID A B C
0 p 1 3 2
1 q 4 3 2
2 r 4 0 9
In [30]: df.set_index('ID',inplace=True)
In [31]: df
Out[31]:
A B C
ID
p 1 3 2
q 4 3 2
r 4 0 9
In [33]: df.to_dict()['B']
Out[33]: {'p': 3, 'q': 3, 'r': 0}
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