anticavity123
anticavity123

Reputation: 111

Mapping dictionary onto dataframe when dictionary key is a list

I have a dictionary where the values are lists:

dict = {1: ['a','b'], 2:['c', 'd']}

I want to map the dictionary onto col1 of my dataframe.

col1    
 a     
 c     

If the value of col1 is IN one of the values of my dictionary, then I want to replace the value of col1 with the value of the dictionary key.

Like this, my dataframe will become:

col1
 1
 2

thanks in advance

Upvotes: 3

Views: 766

Answers (3)

Tai
Tai

Reputation: 7984

You can also try using stack + reset_index and set_index with map.

d = pd.DataFrame({1: ['a','b'], 2:['c', 'd']})
mapping = d.stack().reset_index().set_index(0)["level_1"]
s = pd.Series(['a', 'c'], name="col1")  
s.map(mapping)
0    1
1    2
Name: col1, dtype: int64

Step by step demo

d.stack()

0  1    a
   2    c
1  1    b
   2    d
dtype: object

d.stack().reset_index()

    level_0 level_1 0
0   0          1    a
1   0          2    c
2   1          1    b
3   1          2    d

d.stack().reset_index().set_index(0)

   level_0  level_1
0       
a       0        1
c       0        2
b       1        1
d       1        2

Finally, we select the level_1 column as our mapping to pass in map function.

Upvotes: 1

Giacomo Catenazzi
Giacomo Catenazzi

Reputation: 9523

I would convert the dictionary in the right way:

mapping = {}
for key, values in D.items():
    for item in values:
        mapping[item] = key

and then

df['col1'] = df['col1'].map(mapping)

Upvotes: 2

Kaustubh.P.N
Kaustubh.P.N

Reputation: 239

do you mean something like this???

D = {1 : ['a', 'b'], 2 : ['c', 'd']}

for key, value in D.items():
    for each in value:
        if each in D[key]:
            print(each, "is in D[%s]" % key)

o/p:

a is in D[1]
b is in D[1]
c is in D[2]
d is in D[2]

Upvotes: 0

Related Questions