diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index 7e0931ca1b745..39ff807d6b1e4 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -97,7 +97,7 @@ Categoricals in Series/DataFrame ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :class:`~pandas.Categorical` can now be included in `Series` and `DataFrames` and gained new -methods to manipulate. Thanks to Jan Schultz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`, :issue:`7444`). +methods to manipulate. Thanks to Jan Schultz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`, :issue:`7444`, :issue:`7839`). For full docs, see the :ref:`Categorical introduction ` and the :ref:`API documentation `. diff --git a/pandas/core/series.py b/pandas/core/series.py index 502c01ce6d1d1..c0e1e8a13eea3 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -973,7 +973,9 @@ def _get_repr( return result def __iter__(self): - if np.issubdtype(self.dtype, np.datetime64): + if com.is_categorical_dtype(self.dtype): + return iter(self.values) + elif np.issubdtype(self.dtype, np.datetime64): return (lib.Timestamp(x) for x in self.values) else: return iter(self.values) diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index 0aa7f2b67c7c6..b70e50eb3d030 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -647,6 +647,27 @@ def test_nan_handling(self): np.array(["a","b",np.nan], dtype=np.object_)) self.assert_numpy_array_equal(s3.cat._codes, np.array([0,1,2,0])) + def test_sequence_like(self): + + # GH 7839 + # make sure can iterate + df = DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']}) + df['grade'] = Categorical(df['raw_grade']) + + # basic sequencing testing + result = list(df.grade.cat) + expected = np.array(df.grade.cat).tolist() + tm.assert_almost_equal(result,expected) + + # iteration + for t in df.itertuples(index=False): + str(t) + + for row, s in df.iterrows(): + str(s) + + for c, col in df.iteritems(): + str(s) def test_series_delegations(self):