Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map pandas Dataframe columns to dictionary values

I have a one:many dictionary. I would like to map the values of a pandas Dataframe column to the keys (NOT values) of the dictionary. here is my dictionary:

dict1={'fruits':('apple','grapes','oranges'),'food':('fish','meat','fibre')}

And here is the pandas Series object:

df=pd.Series(['fish','apple','meat'])

the desired output i want:

0      food
1    fruits
2      food
dtype: object
like image 745
Siraj S. Avatar asked May 06 '16 23:05

Siraj S.


People also ask

How do I convert two columns to pandas 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.

How do I convert a Pandas DataFrame to a dictionary?

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.

Can we use map on DataFrame?

Since DataFrame columns are series, you can use map() to update the column and assign it back to the DataFrame.


2 Answers

What if 'other' was in both 'fruits' and 'food'? That is why you cannot do a reverse lookup without having some sort of logic to resolve duplicates.

If your values are all unique, then you can reverse your dictionary using a dictionary comprehension:

reversed_dict = {val: key for key in dict1 for val in dict1[key]}

>>> reversed_dict
{'apple': 'fruits',
 'fibre': 'food',
 'fish': 'food',
 'grapes': 'fruits',
 'meat': 'food',
 'oranges': 'fruits'}

You could then map.

>>> pd.Series(['fish','apple','meat']).map(reversed_dict)
0      food
1    fruits
2      food
dtype: object
like image 196
Alexander Avatar answered Oct 27 '22 09:10

Alexander


Solution

df.apply(lambda x: [k for k in dict1 if x in dict1[k]][0])
like image 44
piRSquared Avatar answered Oct 27 '22 09:10

piRSquared