Python Forum
How to most effectively unpack list of name-value pair dictionaries in a dataframe?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to most effectively unpack list of name-value pair dictionaries in a dataframe?
#2
Updated code to account for potential gaps:

import pandas as pd
import numpy as np

def extract_value(l, name):
    extracted = [item['value'] for item in l if item['name'] == name]
    if len(extracted) == 0:
        return np.nan
    else:
        return extracted[0]

data = {'name': ['Alice', 'Bob', 'Clark'],
        'preferences': [[{'name': 'fruit', 'value': 'apple'}, 
                         {'name': 'drink', 'value': 'lemonade'},
                         {'name': 'food', 'value': 'pizza'}],
                        [{'name': 'fruit', 'value': 'orange'}, 
                         {'name': 'drink', 'value': 'soda'},
                         {'name': 'food', 'value': 'soup'}],
                        [{'name': 'fruit', 'value': 'pear'}, 
                         {'name': 'food', 'value': 'chicken'}]]}
 
df = pd.DataFrame(data)
 
# Extract values from 'preferences' column
df['fruit'] = df['preferences'].apply(lambda x: extract_value(x, 'fruit'))
df['drink'] = df['preferences'].apply(lambda x: extract_value(x, 'drink'))
df['food'] = df['preferences'].apply(lambda x: extract_value(x, 'food'))
 
# Drop the 'preferences' column
df = df.drop(columns=['preferences'])
Reply


Messages In This Thread
RE: How to most effectively unpack list of name-value pair dictionaries in a dataframe? - by zlim - Nov-07-2023, 10:56 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Find duplicates in a pandas dataframe list column on other rows Calab 2 2,582 Sep-18-2024, 07:38 PM
Last Post: Calab
  Find strings by index from a list of indexes in a different Pandas dataframe column Calab 3 1,855 Aug-26-2024, 04:52 PM
Last Post: Calab
Question [Solved] How to refer to dataframe column name based on a list lorensa74 1 3,142 May-17-2021, 07:02 AM
Last Post: lorensa74
  Comparing results within a list and appending to pandas dataframe Aryagm 1 3,080 Dec-17-2020, 01:08 PM
Last Post: palladium
  How to form a dataframe reading separate dictionaries from .txt file? Doug 1 5,356 Nov-09-2020, 09:24 AM
Last Post: PsyPy
  Computing the distance between each pair of points Truman 11 6,597 Jun-20-2020, 01:15 PM
Last Post: Truman
  how to list/count the number of dictionaries paul18fr 2 2,969 Nov-18-2019, 09:50 PM
Last Post: paul18fr
  Creating A List of DataFrames & Manipulating Columns in Each DataFrame firebird 1 5,530 Jul-31-2019, 04:04 AM
Last Post: scidam
  Inserting data from python list into a pandas dataframe mahmoud899 0 3,138 Mar-02-2019, 04:07 AM
Last Post: mahmoud899
  List and Dictionaries with Pandas Balinor 3 4,026 Aug-20-2018, 10:47 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020