Python Forum
Key length (2) exceeds index depth (1) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Key length (2) exceeds index depth (1) (/thread-16750.html)



Key length (2) exceeds index depth (1) - igodspeed - Mar-13-2019

Hello,
I am new to python and i am not sure why i am getting this error

a = np.random.standard_normal((9, 4))
a.round(6)

df = pd.DataFrame(a)
df.columns = [['No1', 'No2', 'No3', 'No4']]
Easy enough till here however when i am trying to

df['No2'][3]
# value in column No2 at index position 3 
i get the following error:

---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-42-c528cbab0606> in <module>()
----> 1 df['No1',3]

/home/inderjeeet/anaconda2/lib/python2.7/site-packages/pandas/core/frame.pyc in __getitem__(self, key)
2684 return self._getitem_frame(key)
2685 elif is_mi_columns:
-> 2686 return self._getitem_multilevel(key)
2687 else:
2688 return self._getitem_column(key)

/home/inderjeeet/anaconda2/lib/python2.7/site-packages/pandas/core/frame.pyc in _getitem_multilevel(self, key)
2728
2729 def _getitem_multilevel(self, key):
-> 2730 loc = self.columns.get_loc(key)
2731 if isinstance(loc, (slice, Series, np.ndarray, Index)):
2732 new_columns = self.columns[loc]

/home/inderjeeet/anaconda2/lib/python2.7/site-packages/pandas/core/indexes/multi.pyc in get_loc(self, key, method)
2246 if self.nlevels < keylen:
2247 raise KeyError('Key length ({0}) exceeds index depth ({1})'
-> 2248 ''.format(keylen, self.nlevels))
2249
2250 if keylen == self.nlevels and self.is_unique:

KeyError: 'Key length (2) exceeds index depth (1)'


I am not sure where the error is at kindly please advise. Any help would be appreaciated!!!


RE: Key length (2) exceeds index depth (1) - Larz60+ - Mar-13-2019

did you mean:
a = np.random.standard_normal(size=(9,4))



RE: Key length (2) exceeds index depth (1) - igodspeed - Mar-13-2019

(Mar-13-2019, 01:10 PM)Larz60+ Wrote: did you mean:
 a = np.random.standard_normal(size=(9,4)) 

I am still getting the same error when i try
df['No2'][3]
.

Thank for your help


RE: Key length (2) exceeds index depth (1) - Larz60+ - Mar-13-2019

That is a new error, the solution I show is for your line 1 which would fail as stated


RE: Key length (2) exceeds index depth (1) - scidam - Mar-14-2019

It is better to use .iloc, .loc, .ix Pandas indexiers, e.g.
df.loc[3, 'No2']
or
df.loc[:,'No2'].ix[3]