Redratz
Redratz

Reputation: 136

Expand Pandas DF Column of a list of dictionaries into separate columns

I have a pandas df that looks like:

enter image description here

The column 'poolData' is a list of dictionaries, here is an example of what that column looks like:

enter image description here

I need to map the dictionary so that each value in 'PoolType' becomes a separate column with the 'Amount' value as the value for that cell.

Here is an example of what I'm trying to achieve.

id_horse Win Place Show
21245 458.00 96.00 36.00
12330 673.00 287.00 205.00
15860 0 0 0
15620 89.00 287.00 36.00

Upvotes: 0

Views: 368

Answers (1)

Ángel Igualada
Ángel Igualada

Reputation: 891

You could do it with apply. In this example, I separate the fields and convert them to float.


data = [{"col": [{"PoolType": "WIN", "Amount": "458.00", "FactionalOdds": "2-1", "Dollar": "6.60"},
       {"PoolType": "PLACE", "Amount": "458.00", "FactionalOdds": "2-1", "Dollar": "6.60"},
       {"PoolType": "SHOW", "Amount": "458.00", "FactionalOdds": "2-1", "Dollar": "6.60"}]},
{"col": [{"PoolType": "WIN", "Amount": "458.00", "FactionalOdds": "2-1", "Dollar": "6.60"},
       {"PoolType": "PLACE", "Amount": "458.00", "FactionalOdds": "2-1", "Dollar": "6.60"},
       {"PoolType": "SHOW", "Amount": "458.00", "FactionalOdds": "2-1", "Dollar": "6.60"}]}]


def separate_column(row):
    for e in row["col"]:
        row[e["PoolType"]] = float(e["Amount"])
    return row

df = pd.DataFrame(data)
df["WIN"] = None
df["PLACE"] = None
df["SHOW"] = None
df = df.apply(separate_column,axis=1)

Upvotes: 2

Related Questions