Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values from a list of dictionaries in a Pandas Dataframe

Tags:

python

pandas

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.

like image 941
Exige304 Avatar asked Nov 01 '25 06:11

Exige304


2 Answers

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]
like image 55
Chris Adams Avatar answered Nov 03 '25 20:11

Chris Adams


Let us use pandas get using series.str.get

df['name']=df.col.str.get('name')
df
                                 col  name
0   {'name': 'Tom', 'hw': [180, 79]}   Tom
1  {'name': 'Mark', 'hw': [119, 65]}  Mark
like image 30
BENY Avatar answered Nov 03 '25 22:11

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!