从数据框列中的字典中提取值

时间:2021-01-11 21:16:19

标签: python pandas dataframe

我有一个带有字典的列的 DataFrame。 我需要从字典中提取一个值。

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}

我尝试只从权重列中获取值

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

我做错了什么?

1 个答案:

答案 0 :(得分:0)

想通了。

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