Vasuvius
Vasuvius

Reputation: 159

Extract value from dictionary in dataframe column

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

Answers (3)

ForceBru
ForceBru

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

Poonacha
Poonacha

Reputation: 1316

You can also use .str[]

df.weight.str['weight']

Upvotes: 3

Vasuvius
Vasuvius

Reputation: 159

figured it out.

df['newweight'] = df.weight.apply(lambda x: x['weight'])

Upvotes: 2

Related Questions