Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing Dictionary Elements from Pandas DataFrame

I have a column of dictionaries like this:

id                            element
 1  {'Colour': 'Grey', 'Brand': 'AB'}
 2   {'Colour': 'Blue', 'Brand': 'B'}
 3   {'Colour': 'Red', 'Brand': 'AH'}

And I want to create new columns from those dictionaries, like this:

id                            element  colour  brand
 1  {'Colour': 'Grey', 'Brand': 'AB'}    Grey     AB
 2   {'Colour': 'Blue', 'Brand': 'B'}    Blue      B
 3   {'Colour': 'Red', 'Brand': 'AH'}     Red     AH

I have done the following but it’s not working:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def whatever(row):
    tmp_d = {}
    for d in row.values:
        for k in d.keys():
            if k in tmp_d.keys():
                tmp_d[k] += 1
            else:
                tmp_d[k] = 1
    return tmp_d
    

new_df.colour = df.groupby('element')'element'].apply(whatever).unstack().fillna(0)

>Solution :

You can also use str.get method to get values under a specific key:

df = df.assign(**{key: df['element'].str.get(key) for key in ('Colour','Brand')})

Output:

   id                            element Colour Brand
0   1  {'Colour': 'Grey', 'Brand': 'AB'}   Grey    AB
1   2   {'Colour': 'Blue', 'Brand': 'B'}   Blue     B
2   3   {'Colour': 'Red', 'Brand': 'AH'}    Red    AH
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading