Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dataframe to dict such that one column is the key and the other is the value [duplicate]

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

like image 230
oren_isp Avatar asked Dec 27 '18 07:12

oren_isp


People also ask

How do you create a dictionary from a column in a data frame?

You can use df. to_dict() in order to convert the DataFrame to a dictionary.

How do I convert a two column DataFrame to a dictionary in Pandas?

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.

What does to_dict do in Python?

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).

Is Pandas DataFrame a dictionary?

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.


1 Answers

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}
like image 153
Mayank Porwal Avatar answered Sep 21 '22 08:09

Mayank Porwal