Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

Pandas/Python Map dictionary keys with multiples values

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

question from:https://stackoverflow.com/questions/65888272/pandas-python-map-dictionary-keys-with-multiples-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...