Python Forum
Key length (2) exceeds index depth (1)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Key length (2) exceeds index depth (1)
#1
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!!!
Reply
#2
did you mean:
a = np.random.standard_normal(size=(9,4))
Reply
#3
(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
Reply
#4
That is a new error, the solution I show is for your line 1 which would fail as stated
Reply
#5
It is better to use .iloc, .loc, .ix Pandas indexiers, e.g.
df.loc[3, 'No2']
or
df.loc[:,'No2'].ix[3]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Getting Index Error - list index out of range krishna 2 2,603 Jan-09-2021, 08:29 AM
Last Post: buran
  Getting Index Error - list index out of range RahulSingh 2 6,143 Feb-03-2020, 07:17 AM
Last Post: RahulSingh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020