如何在 Pandas 中使用 apply 进行嵌套循环

萨里

我有一个这样的数据框:

text,                pos
No thank you.        [(No, DT), (thank, NN), (you, PRP)]
They didn't respond  [(They, PRP), (didn't, VBP), (respond, JJ)]

我想应用一个函数pos并将结果保存在一个新列中。所以输出看起来像这样:

text,                pos                                           score
No thank you.        [(No, DT), (thank, NN), (you, PRP)]        [[0.0, 0.0, 1.0], [], [0.5, 0.0, 0.45]]
They didn't respond  [(They, PRP), (didn, VBP), (respond, JJ)]  [[0.0, 0.0, 1.0], [], [0.75, 0.0, 0.25]]

所以函数为列表中的每个元组返回一个列表(但函数的实现不是这里的重点,为此我只是调用get_sentiment)。我可以使用嵌套循环来做到这一点,但我不喜欢它。我想使用更 Pythonic 和 Pandas Dataframe 的方式来做到这一点:

这是我迄今为止尝试过的:

df['score'] = df['pos'].apply(lambda k: [get_sentiment(x,y) for j in k for (x,y) in j])

但是,它会引发此错误:

ValueError: too many values to unpack (expected 2)

有几个问题,但答案是在 R 中。

为了更清楚:

get_sentiment函数是一个函数,NLTK它为每个单词分配一个分数列表(列表是[positive score, negative score, objectivity score])。总的来说,我需要在pos我的 Dataframe 列的顶部应用该函数

贝尼

在你的情况下

df['score'] = df['pos'].apply(lambda k: [get_sentiment(j[0],j[1]) for j in k ])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章