6

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.

4
  • 8
    What is brics.columns ? I think there is whitespace in column names. Then use brics.columns = brics.columns.str.strip() Commented Aug 31, 2016 at 8:29
  • Shouldn't it be brics.loc[:, 'country':'capital'] ? Commented Aug 31, 2016 at 8:32
  • 2
    @NickilMaveli - yes, it is another solution, but OP code is working nice too. Commented Aug 31, 2016 at 8:33
  • 1
    jezrael, you were right, thank you very much. There was white space in the column labels. Commented Aug 31, 2016 at 21:17

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.