Skip to content

Commit 2b68a97

Browse files
committed
BUG: Series.__iter__ not dealing with category type well (GH7839)
1 parent a23c6c7 commit 2b68a97

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

doc/source/v0.15.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ Categoricals in Series/DataFrame
9797
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
9898

9999
:class:`~pandas.Categorical` can now be included in `Series` and `DataFrames` and gained new
100-
methods to manipulate. Thanks to Jan Schultz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`, :issue:`7444`).
100+
methods to manipulate. Thanks to Jan Schultz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`, :issue:`7444`, :issue:`7839`).
101101

102102
For full docs, see the :ref:`Categorical introduction <categorical>` and the :ref:`API documentation <api.categorical>`.
103103

pandas/core/series.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -973,7 +973,9 @@ def _get_repr(
973973
return result
974974

975975
def __iter__(self):
976-
if np.issubdtype(self.dtype, np.datetime64):
976+
if com.is_categorical_dtype(self.dtype):
977+
return iter(self.values)
978+
elif np.issubdtype(self.dtype, np.datetime64):
977979
return (lib.Timestamp(x) for x in self.values)
978980
else:
979981
return iter(self.values)

pandas/tests/test_categorical.py

+21
Original file line numberDiff line numberDiff line change
@@ -647,6 +647,27 @@ def test_nan_handling(self):
647647
np.array(["a","b",np.nan], dtype=np.object_))
648648
self.assert_numpy_array_equal(s3.cat._codes, np.array([0,1,2,0]))
649649

650+
def test_sequence_like(self):
651+
652+
# GH 7839
653+
# make sure can iterate
654+
df = DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})
655+
df['grade'] = Categorical(df['raw_grade'])
656+
657+
# basic sequencing testing
658+
result = list(df.grade.cat)
659+
expected = np.array(df.grade.cat).tolist()
660+
tm.assert_almost_equal(result,expected)
661+
662+
# iteration
663+
for t in df.itertuples(index=False):
664+
str(t)
665+
666+
for row, s in df.iterrows():
667+
str(s)
668+
669+
for c, col in df.iteritems():
670+
str(s)
650671

651672
def test_series_delegations(self):
652673

0 commit comments

Comments
 (0)