Skip to content
Advertisement

KeyError when using loc from pandas

I have a simple CSV-file which I import as a dataframe. Using df.columns I get the following:

Index(['Unnamed: 0', 'age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6', 'target'], dtype='object')

So there definitely is a column named sex. When now using

df.loc["sex"]

I get the following output:

  File "c:/Users/xxx/OneDrive - Universität Paderborn/Universität/SS_21/Python_Kurse/Hello-World.py", line 37, in <module>
    df.loc["axe"]
  File "C:xxxxminiconda3libsite-packagespandascoreindexing.py", line 895, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "C:xxxxxminiconda3libsite-packagespandascoreindexing.py", line 1124, in _getitem_axis
    return self._get_label(key, axis=axis)
  File "C:xxxxminiconda3libsite-packagespandascoreindexing.py", line 1073, in _get_label
    return self.obj.xs(label, axis=axis)
  File "C:xxxxminiconda3libsite-packagespandascoregeneric.py", line 3739, in xs
    loc = index.get_loc(key)
  File "C:xxxxminiconda3libsite-packagespandascoreindexesrange.py", line 354, in get_loc
    raise KeyError(key)
KeyError: 'axe'

Advertisement

Answer

You also need to give index like

df.loc[index,"sex"]

For example:

df.loc[1,"sex"]

If you only want to get sex column:

df["sex"]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement