简体   繁体   English

从 dataframe 列中的字典中提取值

[英]Extract value from dictionary in dataframe column

I have a DataFrame with a column with dictionaries.我有一个带有字典列的 DataFrame。 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?我做错了什么?

x.get ('value') would look for the key called 'value' , but your dictionary has only one key called 'weight' . x.get ('value')会查找名为'value'的键,但您的字典只有一个名为'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. dict.get专门设计为在您尝试get不存在的 key 的值时返回None ,这正是这里发生的事情。

figured it out.弄清楚了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM