I have a dataframe (table) where one column consists of a list of dictionary key-values
Trip number | location | airlines |
---|---|---|
13452 | [{‘Name’: ‘Japan’, ‘City’: ‘Tokyo’, ‘Continent’: ‘Asia’}, | British Airways |
{‘Name’: ‘United Kingdom’, ‘City’: ‘London’, ‘Continent’: ‘Europe’}, | ||
{‘Name’: ‘Australia’, ‘City’: ‘Sydney’, ‘Continent’: ‘Australia’}] |
| 13567 | [{‘Name’: ‘China’, ‘City’: ‘Hong Kong’, ‘Continent’: ‘Asia’}, |Emirates
| | {‘Name’: ‘India’, ‘City’: ‘Calcutta’, ‘Continent’: ‘Asia’}] |
| 13768 | [{‘Name’: ‘France’, ‘City’: ‘Paris’, ‘Continent’: ‘Europe’}, |Air France
| | {‘Name’: ‘Italy’, ‘City’: ‘Rome’, ‘Continent’: ‘Europe’}, |
| | {‘Name’: ‘Egypt’, ‘City’: ‘Cairo’, ‘Continent’: ‘Africa’}] |
I want to produce the below dataframe (table) where the values for certain keys, in this case ‘Name’ are left.
Trip number | location | airlines |
---|---|---|
13452 | Japan, United Kingdom, Australia | British Airways |
13567 | China, India | Emirates |
13768 | France’, Italy, Egypt | Air France |
I think I need to use a list comprehension method to solve this.
df[‘location’] = [d.get(‘Name’) for d in df[‘location’]]
OR
creating a new ‘name’ column
df[‘name’] =[[d.get(‘Name’) for d in x] for x in df[‘location’]]
I get an error with these though:
AttributeError: ‘str’ object has no attribute ‘get’