From e8fc1c0c7089979ccbf2b749da1987444cad9171 Mon Sep 17 00:00:00 2001 From: Wes McKinney Date: Mon, 7 May 2012 14:23:40 -0400 Subject: [PATCH] BUG: imprecise logic leading to malformed Series in Series.apply, close #1183 --- pandas/core/series.py | 4 +++- pandas/tests/test_series.py | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/pandas/core/series.py b/pandas/core/series.py index 6498abc8f7986..032529676c552 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1872,8 +1872,10 @@ def apply(self, func): """ try: result = func(self) - if not isinstance(result, Series): + if isinstance(result, np.ndarray): result = Series(result, index=self.index, name=self.name) + else: + raise ValueError('Must yield array') return result except Exception: mapped = lib.map_infer(self.values, func) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index baa09a36a8b91..d96e246906784 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -2069,6 +2069,19 @@ def test_apply(self): result = self.ts.apply(lambda x: x.values * 2) assert_series_equal(result, self.ts * 2) + def test_apply_same_length_inference_bug(self): + s = Series([1, 2]) + f = lambda x: (x, x + 1) + + result = s.apply(f) + expected = s.map(f) + assert_series_equal(result, expected) + + s = Series([1, 2, 3]) + result = s.apply(f) + expected = s.map(f) + assert_series_equal(result, expected) + def test_align(self): def _check_align(a, b, how='left', fill=None): aa, ab = a.align(b, join=how, fill_value=fill)