Get values from a list of dictionaries in a Pandas Dataframe

Exige304 :

Okay, so I have a dataframe. Each element of column 'z' is a list of dictionaries.

For example, row two of column 'z' looks like this:

[ {'name': 'Tom', 'hw': [180, 79]},
  {'name': 'Mark', 'hw': [119, 65]} ]

I would like it to just contain the 'name' values, in this case the element would be Tom and Mark without the 'hw' values.

I've tried converting it into a list, then removing every second element, but I lost which values came from the same row. Not every row has the same number of elements in it, some have 2 names, some might have 4.

Chris A :

One way using list comprehension with dict.get:

Example

df = pd.DataFrame({'z': [[{'name': 'Tom', 'hw': [180, 79]},
                         {'name': 'Mark', 'hw': [119, 65]}]]})

df['name'] = [[d.get('name') for d in x] for x in df['z']]

[out]

                                                   z         name
0  [{'name': 'Tom', 'hw': [180, 79]}, {'name': 'M...  [Tom, Mark]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31653&siteId=1