我有一个如下所示的数据框:
Text
0 this is amazing
1 nan
2 wow you are great
我想将数据帧单元格中的每个单词迭代到 textblob 中,以获取新列中的极性。然而,许多行中都有 nan
。
我认为这导致 TextBlob 在新列中的所有行(甚至其中包含文本的行)的极性得分为 0.0。
如何对列中的每个文本运行 TextBlob.sentiment.polarity 并使用极性分数创建一个新列?
新的 df 应如下所示:
Text sentiment
0 this is amazing 0.9
1 nan 0.0
2 wow you are great 0.8
我不关心 nan
,因此情绪值可以是 nan
或 0。
当前代码不起作用:
for text in df.columns:
a = TextBlob(text)
df['sentiment']=a.sentiment.polarity
print(df.value)
提前谢谢您。
编辑:
要补充的是,不确定这是否有区别,df 上的索引不会重置,因为 df 的其他部分按相同的索引号分组在一起。
最佳答案
试试这个:
>>> s=pd.Series(['this is amazing',np.NaN,'wow you are great'],name='Text')
>>> s
Out[100]:
0 this is amazing
1 NaN
2 wow you are great
Name: Text, dtype: object
>>> s.apply(lambda x: np.NaN if pd.isnull(x) else TextBlob(x).sentiment.polarity)
Out[101]:
0 0.60
1 NaN
2 0.45
Name: Text, dtype: float64
关于python - 如果某些行的列中的值丢失,如何应用 TextBlob?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51883947/