0

I was wondering how I can map a dictionary key with multiple dictionary items. I have tried the below however the output is not the expected one.

d = {'col1': ['type 2','type 3', 'type 4', 'type 5', 'type 6', 'type 6']}
df = pd.DataFrame(data=d)

dict = {
    'a' :['type 2', 'type 3'],
    'b' : ['type 4', 'type 5'],
    'c': ['types 6', 'types 7']
}

for k, v in df.items():
    df['col1'].map({k: v})
    print(df)

expected output: enter image description here

2 Answers 2

1

You may have to convert your dict such that the keys are values and vice versa.

dd = {
    'a' :['type 2', 'type 3'],
    'b' : ['type 4', 'type 5'],
    'c': ['type 6', 'type 7']
}
ddd = {l:v for v,k in dd.items() for l in k}
print(ddd)

Out:

{'type 2': 'a',
 'type 3': 'a',
 'type 4': 'b',
 'type 5': 'b',
 'type 6': 'c',
 'type 7': 'c'}

Now you can map it easily.

df.col1.map(ddd)

Out:

0    a
1    a
2    b
3    b
4    c
5    c
Name: col1, dtype: object
Sign up to request clarification or add additional context in comments.

Comments

0

We can try explode

s = pd.Series(d).explode()
df['col1'] = df['col1'].map(dict(zip(s,s.index)))

Input

d= {
    'a' :['type 2', 'type 3'],
    'b' : ['type 4', 'type 5'],
    'c': ['type 6', 'type 7']
}

Notice : do not named a variable same as original function from python or pandas

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.