在 Python 中计算极性时接收密钥错误 = 0

问题描述

我有两列 - texttitle 用于新闻文章

数据看起来不错,为打印屏幕道歉,只是为了显示结构。

但是当我尝试计算极性时,它给了我一个奇怪的错误

# Create
polarity = []

# Creare for loop for Text column only
for i in range(len(jordan_df['text'])):
    polarity.append(TextBlob(jordan_df['text'][i]).sentiment.polarity)

# Put data together    
polarity_data = {'article_text':jordan_df['text'],'article_polarity': polarity}

当我用相同的结构将 jordan_df 更改为 some_df 时,这段代码的作用很奇怪。

错误

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self,key,method,tolerance)
2897             try:
-> 2898                 return self._engine.get_loc(casted_key)
2899             except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

**KeyError: 0**

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
3 frames
<ipython-input-186-edab50678cab> in <module>()
  9 # Creare for loop for Text column only
 10 for i in range(len(jordan_df['text'])):
---> 11     polarity.append(TextBlob(jordan_df['text'][i]).sentiment.polarity)
 12 
 13 # Put data together

/usr/local/lib/python3.7/dist-packages/pandas/core/series.py in __getitem__(self,key)
880 
881         elif key_is_scalar:
--> 882             return self._get_value(key)
883 
884         if is_hashable(key):

/usr/local/lib/python3.7/dist-packages/pandas/core/series.py in _get_value(self,label,takeable)
988 
989         # Similar to Index.get_value,but we do not fall back to positional
--> 990         loc = self.index.get_loc(label)
991         return self.index._get_values_for_loc(self,loc,label)
992 

/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self,tolerance)
2898                 return self._engine.get_loc(casted_key)
2899             except KeyError as err:
-> 2900                 raise KeyError(key) from err
2901 
2902         if tolerance is not None:

解决方法

在您的代码中添加这一行:

polarity = []

jordan_df.reset_index(drop=True,inplace = True)  #add this line


# Creare for loop for Text column only
for i in range(len(jordan_df['text'])):
    polarity.append(TextBlob(jordan_df['text'][i]).sentiment.polarity)

# Put data together    
polarity_data = {'article_text':jordan_df['text'],'article_polarity': polarity}

您可能过滤掉了结果,它改变了您的 jordan_df 中的索引。您可以在 head()jordan_df 中看到索引以 7 开头。

这就是您在密钥 KeyError 上获得 0 的原因

即当 i=0jordan_df['text'][i]