【问题标题】:KeyError when creating new column in python pandas在 python pandas 中创建新列时出现 KeyError
【发布时间】:2019-02-26 18:35:08
【问题描述】:

我正在尝试在 python pandas 中创建一个新列,但我不断收到一个(不稳定的)重复发生的 KeyError。该脚本的部分非常简单,因此我不确定是什么导致了错误,因为数据集中没有任何列具有相同的名称。

我的目标是创建一个新列并将其附加到包含该列 ticket_contents 内容的新翻译的数据框中。 这是数据样本;

25483   0   outstanding 0   Los-Angeles e-payment   delayed Ticket  1/7/19 7:54
39363   0   outstanding 0   Los-Angeles e-payment   delayed Ticket  1/7/19 7:54
83584   0   outstanding 6   Los-Angeles e-payment   delayed Ticket  1/7/19 7:54
34537   0   outstanding 7   Los-Angeles e-payment   lost    Ticket  1/7/19 7:53



colnames = ['id', 'ln_id', 'status', 
'number_outstanding', 'country', 'subject', 'ticket_contents', 'subtopic', 
'date']
test_data = pandas.read_csv(test_data, names = colnames, encoding 
= 'utf-8')
test_data = pandas.DataFrame(test_data)

translated_description = []

from_lang = 'tl'
to_lang = 'en-us'

def test_translation(contents):
    translator = Translator(from_lang = from_lang, to_lang = to_lang)
    translation = translator.translate(contents)
    translated_description.append(translation)
    #print(translated_description)


for contents, row in test_data.iterrows():
    contents = test_data.ticket_contents.iloc[contents -1]
    test_translation(contents)

test_data['translated_descriptions'].copy = translated_description

这是错误输出:

KeyError Traceback (most recent call last)
<ipython-input-70-55e39cf5e328> in <module>()
     16     test_translation(contents)
     17 
---> 18 test_data['translated_descriptions'].copy = translated_description
     19 

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/frame.pyc in __getitem__(self, key)
   1962             return self._getitem_multilevel(key)
   1963         else:
-> 1964             return self._getitem_column(key)
   1965 
   1966     def _getitem_column(self, key):

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/frame.pyc in _getitem_column(self, key)
   1969         # get column
   1970         if self.columns.is_unique:
-> 1971             return self._get_item_cache(key)
   1972 
   1973         # duplicate columns & possible reduce dimensionality

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/generic.pyc in _get_item_cache(self, item)
   1643         res = cache.get(item)
   1644         if res is None:
-> 1645             values = self._data.get(item)
   1646             res = self._box_item_values(item, values)
   1647             cache[item] = res

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/internals.pyc in get(self, item, fastpath)
   3588 
   3589             if not isnull(item):
-> 3590                 loc = self.items.get_loc(item)
   3591             else:
   3592                 indexer = np.arange(len(self.items))[isnull(self.items)]

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/indexes/base.pyc in get_loc(self, key, method, tolerance)
   2442                 return self._engine.get_loc(key)
   2443             except KeyError:
-> 2444                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2445 
   2446         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5280)()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5126)()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas/_libs/hashtable.c:20523)()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas/_libs/hashtable.c:20477)()

KeyError: u'translated_descriptions'

【问题讨论】:

  • 您应该提供来自test_data 的代码格式示例。
  • 你不应该修改你正在迭代的东西 DataFrame.iterrows() documentation。请提供示例输入和输出,以便清楚您要实现的目标。

标签: python pandas keyerror


【解决方案1】:

我同意 cmets 的观点,即您不应该遍历数据框。您应该将所有值计算到一个列表、数组或系列中,并一次性分配它们。

但是你的错误来自这一行:

test_data['translated_descriptions'].copy = translated_description

它所做的是覆盖test_data['translated_descriptions'] 系列的copy 属性/方法。由于该系列尚不存在,因此您会收到错误消息。

要使用您的值序列创建一个新列,我会执行以下操作:

test_data = test_data.assign(translated_descriptions=translated_description_values)

【讨论】:

  • 我认为这就是我正在做的事情。我在循环之前创建了空列表 translate_descriptions 。然后我将结果附加到列表中。然后在所有翻译都在列表中之后,即当我将它添加到数据框时。有没有更好的方法来做到这一点?
  • @chaimocha 我无法真正遵循您的代码 b/c 它不可重现。但这是一个侧面/优化问题。按照我的答案末尾提出的解决方案,如果它引发相同的错误,请报告
【解决方案2】:

错误发生在:

test_data['translated_descriptions'].copy = translated_description

它实际上包含什么:

  • test_data['translated_descriptions'].copy - 是对尚未不存在列的copy方法的引用。
  • ... = translated_description - 您尝试将列表替换为 这个参考。

如果你想创建一个新列,只需写:

test_data['translated_descriptions'] = translated_description

编辑

如果你想摆脱评论中提到的错误,那么:

  • 从复制数据框开始:df2 = test_data.copy() (调用整个 DataFrame 的copy 方法,而不是它的列)。
  • 然后使用df2 - 新的DataFrame。

以及如何改进程序的一些提示:

在翻译函数之外定义translator

translator = Translator(from_lang = from_lang, to_lang = to_lang)

然后定义翻译函数为:

def test_translation(contents):
    return translator.translate(contents)

然后可以像这样简单地创建新的列:

test_data['translated_descriptions'] = \
    test_data.ticket_contents.apply(test_translation)

没有任何中间列表。

还请查看您的程序的以下片段:

test_data = pandas.read_csv(test_data, names = colnames,
    encoding = 'utf-8')
test_data = pandas.DataFrame(test_data)

注意:

  • 第一条指令从 CSV 文件中读取 DataFrame 并保存 在test_data 变量下。
  • 然后创建下一个 DataFrame(实际上是现有的视图 DataFrame),并将其分配给相同的变量。

结果是:

  • previous DataFrame 存在于某处,但现在无法访问。
  • 您可以访问使用第二条指令创建的视图。
  • 这就是您收到上述错误的原因。

结论:删除第二条指令。有一个就足够了 数据帧。

【讨论】:

  • 这是我原来的那行,但我添加了'.copy'以绕过错误A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead
猜你喜欢
  • 2018-04-07
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多