I dont understand why I am receiving this error.
KeyError: u'the label [ContractType] is not in the [index]'
I have a simple csv file that is passed in by:
df = pd.read_csv(filename, encoding="utf-8")
My goal is to replace, empty cells in a column with another text, but whenever I try to use the .loc method i receive a key error.
df = df.astype(object).where(df.loc['ContractType'] == "not available","non-specified")
Resource: Similar solution
What generates the error
df.loc['ContractType']
Verifying that it is a valid key I have verified that the key is a valid key by using this code:
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()
Output:
<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')
I have even tried:
print df.loc[df.keys()[3]]
I don't know why I am getting this error, even when it is a valid key?
Error Output
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]'