From 745a49623fbce3a5b0ea761c726eb1d0e3ac155f Mon Sep 17 00:00:00 2001 From: Wes McKinney Date: Sat, 11 Aug 2012 23:39:33 -0400 Subject: [PATCH] ENH: handle generators in Series constructor close #1679 --- RELEASE.rst | 1 + pandas/core/series.py | 3 +++ pandas/tests/test_series.py | 12 ++++++++++++ 3 files changed, 16 insertions(+) diff --git a/RELEASE.rst b/RELEASE.rst index af750cc234b60..f6b3dc53a7585 100644 --- a/RELEASE.rst +++ b/RELEASE.rst @@ -35,6 +35,7 @@ pandas 0.8.2 - Add ``flags`` option for ``re.compile`` in some Series.str methods (#1659) - Parsing of UTC date strings in read_* functions (#1693) + - Handle generator input to Series (#1679) **API Changes** diff --git a/pandas/core/series.py b/pandas/core/series.py index 25909206395cf..a2275fe40cf68 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -8,6 +8,7 @@ from itertools import izip import operator from distutils.version import LooseVersion +import types from numpy import nan, ndarray import numpy as np @@ -323,6 +324,8 @@ def __new__(cls, data=None, index=None, dtype=None, name=None, data = lib.fast_multiget(data, index.values, default=np.nan) except TypeError: data = [data.get(i, nan) for i in index] + elif isinstance(data, types.GeneratorType): + data = list(data) if dtype is not None: dtype = np.dtype(dtype) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index f04f881b83c86..eb3b074da4679 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -270,6 +270,18 @@ def test_constructor_series(self): assert_series_equal(s2, s1.sort_index()) + def test_constructor_generator(self): + gen = (i for i in range(10)) + + result = Series(gen) + exp = Series(range(10)) + assert_series_equal(result, exp) + + gen = (i for i in range(10)) + result = Series(gen, index=range(10, 20)) + exp.index = range(10, 20) + assert_series_equal(result, exp) + def test_constructor_maskedarray(self): data = ma.masked_all((3,), dtype=float) result = Series(data)