Skip to content Skip to sidebar Skip to footer

Parsing Nested Dictionary To Dataframe

I am trying to create data frame from a JSON file. and each album_details have a nested dict like this {'api_path': '/albums/491200', 'artist': {'api_path': '/artists/1421',

Solution 1:

Is that is the case use str to call the dict key

df['name'] = df['album_details'].str['name']

Solution 2:

If you have the dataframe stored in the df variable you could do:

df['artist_name'] = [x['artist']['name'] for x in df['album_details'].values]

Solution 3:

You can use apply with lambda function:

df['album_name'] = df['album_details'].apply(lambda d: d['name'])

Basically you execute the lambda function for each value of the column 'album_details'. Note that the argument 'd' in the function is the album dictionary. Apply returns a series of the function return values and this you can set to a new column.

See: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html

Post a Comment for "Parsing Nested Dictionary To Dataframe"