Reputation: 159
I have a DataFrame with a column with dictionaries. I need to extract a value from the dictionary.
df = pd.DataFrame(x.edges(data=True), columns=['emp1','emp2','weight'])
emp1 emp2 weight
0 Joan Lee {'weight': 3}
1 Joan Andy {'weight': 1}
2 Vincent Frida {'weight': 2}
I try to get just the value from the weight column
df['newweight'] = df.weight.apply(lambda x: x.get('value'))
emp1 emp2 weight newweight
0 Joan Lee {'weight': 3} None
1 Joan Andy {'weight': 1} None
2 Vincent Frida {'weight': 2} None
What am I doing incorrectly?
Upvotes: 2
Views: 5193
Reputation: 44828
x.get('value')
would look for the key called 'value'
, but your dictionary has only one key called 'weight'
.
dict.get
is specifically designed to return None
when you attempt to get
the value of a nonexistent key, which is exactly what's happening here.
Upvotes: 1
Reputation: 159
figured it out.
df['newweight'] = df.weight.apply(lambda x: x['weight'])
Upvotes: 2