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

Receiving Key Error = 0 while calculating the polarity in Python

我有两栏 - 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, key, method, 
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 中的索引。您可以在 jordan_dfhead() 中看到索引以 7 开头。

这就是为什么你在 Key 0

上得到 KeyError

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