I have a pandas series containing a list of dictionaries. I’d like to parse the contents of the dicts with some condition and store the results into new columns.
Here’s some data to work with:
JavaScript
x
17
17
1
import pandas as pd
2
3
df = pd.DataFrame({'d': [[{'br': 1, 'ba': 1, 'r': 100},
4
{'ba': 1, 'r': 80},
5
{'br': 2, 'ba': 1, 'r': 150},
6
{'br': 1, 'ba': 1, 'r': 90}],
7
[{'br': 1, 'ba': 1, 'r': 100},
8
{'ba': 1, 'r': 80},
9
{'br': 2, 'ba': 1, 'r': 150}]],
10
11
'id': ['xxas', 'yxas'],
12
13
'name': [A, B]
14
15
})
16
17
I’d like to parse the contents of each dictionary with some conditional logic. Check for each dicts in the list and name columns as keys br
and ba
. Get the value
of r
key
as assign as column value. If key is not found, br
in this example, assign 0
as the value. Expected output:
JavaScript
1
9
1
id br ba r name
2
xxas 1 0 100 A
3
xxas 0 1 80 A
4
xxas 2 1 150 A
5
xxas 1 1 90 A
6
yxas 1 1 100 B
7
yxas 0 1 80 B
8
yxas 2 1 150 B
9
Advertisement
Answer
Try:
JavaScript
1
3
1
df = pd.concat([df.pop("d").explode().apply(pd.Series).fillna(0), df], axis=1)
2
print(df[["id", "br", "ba", "r", "name"]].astype(int, errors="ignore"))
3
Prints:
JavaScript
1
9
1
id br ba r name
2
0 xxas 1 1 100 A
3
0 xxas 0 1 80 A
4
0 xxas 2 1 150 A
5
0 xxas 1 1 90 A
6
1 yxas 1 1 100 B
7
1 yxas 0 1 80 B
8
1 yxas 2 1 150 B
9