Home > other >  Create column from dictionary key and merging on list similarity pandas python
Create column from dictionary key and merging on list similarity pandas python

Time:10-26

I have a dictionary like:

{'A':['John','Mark','Jane'],'B':['Mike','Rob','James']}

and a dataframe like:

Name x y
John --- ---
Jane --- ---

I would like to add another column, let's call it 'Group', that fills the dictionary key value if Name matches any one of the inner list items. Ideally will end like this:

Name x y Group
John --- --- A
Rob --- --- B

CodePudding user response:

One solution can be creating inverse dictionary and then use pd.Series.map:

dct = {"A": ["John", "Mark", "Jane"], "B": ["Mike", "Rob", "James"]}

# 1. create inverse dictionary from dct
inv_dct = {v: k for k, l in dct.items() for v in l}    #inv_dct = {'John': 'A', 'Mark': 'A', 'Jane': 'A', 'Mike': 'B', 'Rob': 'B', 'James': 'B'}

# 2. use .map() to create Group column
df["Group"] = df["Name"].map(inv_dct)

# 3. print the dataframe
print(df)

Prints:

   Name    x    y Group
0  John  ---  ---     A
1   Rob  ---  ---     B
  • Related