Reputation: 25999
If I have a dict of lists, and I want to map/replace values in a column to the key of each item if one of the list values match, how can I do this?
For example:
MappingDict = {
'argenx SE': ['argenx SE',
'Argenx SE',
'ARGENX SE',
'ARGENX SE NV',
'ARGENX SE COMMON STOCK',
'ARGENX SE ARGX',
'argenx SE ADR'],
'Arête Industries, Inc': [],
'Ares Management Corporation': ['Ares Management Corporation',
'Ares Management Corporation 7 % Non-Cum Pfd Registered Shs Series A'],
'Alexandria Real Estate Equities, Inc': ['Alexandria Real Estate Equities, Inc',
'Alexandria Real Estate Equities Inc 3.45 04/30/2025',
'Alexandria Real Estate Equities Inc-3.45%-4-30-2025']
}
I have dataframe that looks like this
df['Name']:
Name
Alexandria Real Estate Equities Inc 3.45 04/30/2025
ARGENX SE NV
Arête Industries, Inc
I want it to result to:
df['Name']:
Name
Alexandria Real Estate Equities, Inc
argenx SE
Arête Industries, Inc
Basically if the item in the list of a value matches then it should replace the column's value with the key. If the value of a key is blank then the value should just remain as it is. I've tried to replace and map to do this but it seems they are not designed to work with a dict of lists. What can I do to make this work?
Upvotes: 1
Views: 74
Reputation: 323246
Let us try explode
then replace
s = pd.Series(MappingDict).explode()
df['name_new'] = df.Name.replace(dict(zip(s,s.index)))
df
Name name_new
0 Alexandria Real Estate Equities Inc 3.45 04/30... Alexandria Real Estate Equities, Inc
1 ARGENX SE NV argenx SE
2 Arête Industries, Inc Arête Industries, Inc
Upvotes: 5