1

I have a list of dictionary

items = [{'name':'Fruit','title':'Apple','id':'1'},
{'name':'Fruit','title':'Banana','id':'1'},
{'name':'Vegetable','title':'Tomato','id':'2'},
{'name':'Vegetable','title':'Onion','id':'2'}]

and I have a dataframe

df = pd.Dataframe({'Name': {0: 'Banana', 1: 'Apple', 2: 'Orange', 3: 'Tomato', 4: 'Onion'},'Price': {0: 25, 1: 20, 2: 10, 3: 26, 4: 45},'Kg': {0: 1, 1: 25, 2: 3, 3: 55, 4: 10}})

enter image description here

Now I need to map the title in next column, if the value not exist in dict, it can be Empty

Expected output:

enter image description here

What I have tried is

df["Title"] = df["Name"].map(lambda x : for i in items[name] == x)

Adding a new pandas column with mapped value from a dictionary

But its not working as items is a list of dictonary.

Hirusha Fernando
  • 1,156
  • 10
  • 29
jones
  • 37
  • 3

1 Answers1

1

You can flatten your list into a single dict and use that to map.

df['Title'] = df['Name'].map({i['title']:i['name'] for i in items})
Chris
  • 15,819
  • 3
  • 24
  • 37