我不明白为什么会收到此错误。
KeyError: u'the label [ContractType] is not in the [index]'
我有一个简单的csv文件,该文件由传入:
df = pd.read_csv(filename, encoding="utf-8")
我的目标是用另一个文本替换一列中的空单元格,但是每当我尝试使用.loc方法时,都会收到一个关键错误。
df = df.astype(object).where(df.loc['ContractType'] == "not available","non-specified")
产生错误的原因
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]'