Repository: pandas-dev/pandas

Issue:
Series.at and DataFrame.at crash with CategoricalIndex
#### Code Sample, a copy-pastable example if possible

```python
Python 3.6.3 (default, Oct  3 2017, 21:45:48) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> x = pd.Series([1, 2, 3], index=pd.CategoricalIndex(["A", "B", "C"]))
>>> x.loc["A"]
1
>>> x.at["A"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py", line 1869, in __getitem__
    return self.obj._get_value(*key, takeable=self._takeable)
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/series.py", line 929, in _get_value
    return self.index.get_value(self._values, label)
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/category.py", line 423, in get_value
    return series.iloc[indexer]
AttributeError: 'numpy.ndarray' object has no attribute 'iloc'
>>> x = pd.DataFrame([[1, 2], [3, 4], [5, 6]], index=pd.CategoricalIndex(["A", "B", "C"]))
>>> x.loc["B", 1]
4
>>> x.at["B", 1]
Traceback (most recent call last):
  File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 811, in pandas._libs.hashtable.Int64HashTable.get_item
TypeError: an integer is required

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py", line 1869, in __getitem__
    return self.obj._get_value(*key, takeable=self._takeable)
  File "/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py", line 1985, in _get_value
    return engine.get_value(series._values, index)
  File "pandas/_libs/index.pyx", line 83, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 91, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 141, in pandas._libs.index.IndexEngine.get_loc
KeyError: 'B'
```

#### Problem description

With a `CategoricalIndex`, `Series.at` raises `AttributeError` and `DataFrame.at` raises `TypeError` and `KeyError`.

#### Expected Output

`x.at["A"]` should work the same as `x.loc["A"]`, and `x.at["B", 1]` should work the same as `x.loc["B", 1]`.

#### Output of ``pd.show_versions()``

<details>

commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Linux
OS-release: 4.13.0-37-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.22.0
pytest: 3.4.0
pip: 9.0.3
setuptools: 39.0.1
Cython: None
numpy: 1.14.2
scipy: 1.0.0
pyarrow: None
xarray: None
IPython: None
sphinx: 1.6.7
patsy: 0.4.1
dateutil: 2.7.2
pytz: 2018.3
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 2.2.2
openpyxl: 2.4.9
xlrd: 1.1.0
xlwt: None
xlsxwriter: None
lxml: 4.0.0
bs4: 4.6.0
html5lib: 1.0.1
sqlalchemy: 1.2.0
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

</details>



Discussion:
Thanks for the report, that's clearly a bug. 

Related issue (on indexing with categorical index): https://github.com/pandas-dev/pandas/issues/14865

Resolving patch:
diff --git a/pandas/_typing.py b/pandas/_typing.py
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -8,8 +8,14 @@
 from pandas._libs.tslibs.timedeltas import Timedelta
 
 from pandas.core.dtypes.dtypes import ExtensionDtype
-from pandas.core.dtypes.generic import ABCExtensionArray
+from pandas.core.dtypes.generic import (
+    ABCExtensionArray, ABCIndexClass, ABCSeries, ABCSparseSeries)
 
+AnyArrayLike = Union[ABCExtensionArray,
+                     ABCIndexClass,
+                     ABCSeries,
+                     ABCSparseSeries,
+                     np.ndarray]
 ArrayLike = Union[ABCExtensionArray, np.ndarray]
 DatetimeLikeScalar = Type[Union[Period, Timestamp, Timedelta]]
 Dtype = Union[str, np.dtype, ExtensionDtype]
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2694,13 +2694,19 @@ def _get_value(self, index, col, takeable=False):
 
         try:
             return engine.get_value(series._values, index)
+        except KeyError:
+            # GH 20629
+            if self.index.nlevels > 1:
+                # partial indexing forbidden
+                raise
         except (TypeError, ValueError):
+            pass
 
-            # we cannot handle direct indexing
-            # use positional
-            col = self.columns.get_loc(col)
-            index = self.index.get_loc(index)
-            return self._get_value(index, col, takeable=True)
+        # we cannot handle direct indexing
+        # use positional
+        col = self.columns.get_loc(col)
+        index = self.index.get_loc(index)
+        return self._get_value(index, col, takeable=True)
     _get_value.__doc__ = get_value.__doc__
 
     def set_value(self, index, col, value, takeable=False):
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -1,4 +1,5 @@
 import operator
+from typing import Any
 import warnings
 
 import numpy as np
@@ -17,6 +18,7 @@
 from pandas.core.dtypes.generic import ABCCategorical, ABCSeries
 from pandas.core.dtypes.missing import isna
 
+from pandas._typing import AnyArrayLike
 from pandas.core import accessor
 from pandas.core.algorithms import take_1d
 from pandas.core.arrays.categorical import Categorical, contains
@@ -494,16 +496,31 @@ def get_loc(self, key, method=None):
         except KeyError:
             raise KeyError(key)
 
-    def get_value(self, series, key):
+    def get_value(self,
+                  series: AnyArrayLike,
+                  key: Any):
         """
         Fast lookup of value from 1-dimensional ndarray. Only use this if you
         know what you're doing
+
+        Parameters
+        ----------
+        series : Series, ExtensionArray, Index, or ndarray
+            1-dimensional array to take values from
+        key: : scalar
+            The value of this index at the position of the desired value,
+            otherwise the positional index of the desired value
+
+        Returns
+        -------
+        Any
+            The element of the series at the position indicated by the key
         """
         try:
             k = com.values_from_object(key)
             k = self._convert_scalar_indexer(k, kind='getitem')
             indexer = self.get_loc(k)
-            return series.iloc[indexer]
+            return series.take([indexer])[0]
         except (KeyError, TypeError):
             pass
 


Test patch:
diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py
--- a/pandas/tests/indexing/test_categorical.py
+++ b/pandas/tests/indexing/test_categorical.py
@@ -638,6 +638,16 @@ def test_loc_slice(self):
         # expected = df.iloc[[1,2,3,4]]
         # assert_frame_equal(result, expected)
 
+    def test_loc_and_at_with_categorical_index(self):
+        # GH 20629
+        s = Series([1, 2, 3], index=pd.CategoricalIndex(["A", "B", "C"]))
+        assert s.loc['A'] == 1
+        assert s.at['A'] == 1
+        df = DataFrame([[1, 2], [3, 4], [5, 6]],
+                       index=pd.CategoricalIndex(["A", "B", "C"]))
+        assert df.loc['B', 1] == 4
+        assert df.at['B', 1] == 4
+
     def test_boolean_selection(self):
 
         df3 = self.df3