Python Pandas dataframe使用中的KeyError。

2024-06-26 13:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白为什么我会收到这个错误。在

KeyError: u'the label [ContractType] is not in the [index]'

我有一个简单的csv文件,通过以下方式传入:

^{pr2}$

我的目标是用另一个文本替换列中的空单元格,但每当我尝试使用.loc方法时,都会收到一个键错误。在

df = df.astype(object).where(df.loc['ContractType'] == "not available","non-specified")

资源:Similar solution

是什么产生了错误

df.loc['ContractType']

验证它是否为有效密钥 我已使用以下代码验证密钥是否为有效密钥:

for column in df.columns:
    print type(column),column
print type('Id'),type(u'Id'),type(unicode('Id')),type('Id'.encode('utf-8'))
df.keys()

输出:

<type 'unicode'> Id
<type 'unicode'> xxx
<type 'unicode'> xxx
<type 'unicode'> ContractType
<type 'unicode'> xxx
<type 'unicode'> xxx
<type 'unicode'> xxx
<type 'unicode'> xxx
<type 'unicode'> xxx
<type 'unicode'> xxx
<type 'unicode'> xxx
<type 'str'> <type 'unicode'> <type 'unicode'> <type 'str'>
Index([u'Id', u'xxx', u'xxx', u'ContractType', u'xxx',
   u'xxx', u'xxx', u'xxx', u'xxx',
   u'xxx', u'xxx'],
  dtype='object')

我甚至尝试过:

print df.loc[df.keys()[3]]

我不知道为什么我会得到这个错误,即使它是一个有效的密钥?在

错误输出

KeyErrorTraceback (most recent call last)
<ipython-input-72-c852bdc72c73> in <module>()
  4 print type('Id'),type(u'Id'),type(unicode('Id')),type('Id'.encode('utf- 
8'))
      5 df.keys()
----> 6 df.loc['ContractType']
      7 #print df.loc[df.keys()[3]]
      8 #print df == "not available"

C:\Users\xxx\AppData\Local\Continuum\anaconda2\lib\site- 
packages\pandas\core\indexing.pyc in __getitem__(self, key)
   1371 
   1372             maybe_callable = com._apply_if_callable(key, self.obj)
-> 1373             return self._getitem_axis(maybe_callable, axis=axis)
   1374 
   1375     def _is_scalar_access(self, key):

C:\Users\xxx\AppData\Local\Continuum\anaconda2\lib\site- 
packages\pandas\core\indexing.pyc in _getitem_axis(self, key, axis)
   1624 
   1625         # fall thru to straight lookup
-> 1626         self._has_valid_type(key, axis)
   1627         return self._get_label(key, axis=axis)
   1628 

C:\Users\xxx\AppData\Local\Continuum\anaconda2\lib\site- 
packages\pandas\core\indexing.pyc in _has_valid_type(self, key, axis)
   1512                 raise
   1513             except:
-> 1514                 error()
   1515 
   1516         return True

C:\Users\xxx\AppData\Local\Continuum\anaconda2\lib\site- 
packages\pandas\core\indexing.pyc in error()
   1499                 raise KeyError(u"the label [{key}] is not in the 
[{axis}]"
   1500                                .format(key=key,
-> 1501                                        
axis=self.obj._get_axis_name(axis)))
   1502 
   1503             try:

KeyError: u'the label [ContractType] is not in the [index]'

Tags: thekeyinselfiddftype错误