Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe indexing: KeyError:none of [columns] are in the [columns]

I'm in datacamp's 'Intermediate Python for Data Science'.

>>> brics.loc[:]
          country     capital    area   population
BR         Brazil    Brasilia   8.516       200.40
RU         Russia      Moscow  17.100       143.50
IN          India   New Delhi   3.286      1252.00
CH          China     Beijing   9.597      1357.00
SA   South Africa    Pretoria   1.221        52.98
>>> brics.loc[:,['country','capital']]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 1294, in __getitem__
    return self._getitem_tuple(key)
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 789, in _getitem_tuple
    self._has_valid_tuple(tup)
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 142, in _has_valid_tuple
    if not self._has_valid_type(k, i):
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 1379, in _has_valid_type
    (key, self.obj._get_axis_name(axis)))
    KeyError: "None of [['country', 'capital']] are in the [columns]"

This is textbook indexing, and it worked last night but not today.

>>> brics.iloc[1,1]
' Moscow'
>>> brics.iloc[1,2]
17.100000000000001

It's like my only busted function is loc(); iloc() is selecting fine. The error messages are from pandas so I reinstalled with pip3; it didn't help, did apt-get update upgrade etc, no change.

Looks like for some reason pandas isn't parsing my strings right in the loc method.

like image 451
JCMontalbano Avatar asked Aug 31 '16 08:08

JCMontalbano


1 Answers

Here I wrote simple code using .loc You can see below code

import pandas as pd
df = pd.DataFrame({'num_legs': [2, 4, 8, 0],'num_wings': [2, 0, 0, 0],'num_specimen_seen': [10, 2, 1, 8]},index=['falcon', 'dog', 'spider', 'fish'])
print(df.loc[:, 'num_legs':'num_wings'])

It worked in mycase, You can try this

like image 126
Sai Varun Kumar Avatar answered Nov 03 '22 00:11

Sai Varun Kumar