Skip to content

Commit 3a9c177

Browse files
committed
TST: explicity tests for iterator/generator types in DataFrame/Series construction
ENH: add generator support in DataFrame constructor
1 parent b134121 commit 3a9c177

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

pandas/core/frame.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import sys
1717
import collections
1818
import warnings
19+
import types
1920

2021
from numpy import nan as NA
2122
import numpy as np
@@ -413,7 +414,9 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
413414
else:
414415
mgr = self._init_ndarray(data, index, columns, dtype=dtype,
415416
copy=copy)
416-
elif isinstance(data, list):
417+
elif isinstance(data, (list, types.GeneratorType)):
418+
if isinstance(data, types.GeneratorType):
419+
data = list(data)
417420
if len(data) > 0:
418421
if index is None and isinstance(data[0], Series):
419422
index = _get_names_from_index(data)

pandas/tests/test_frame.py

+25
Original file line numberDiff line numberDiff line change
@@ -2632,6 +2632,31 @@ def __len__(self, n):
26322632
expected = DataFrame({ 'A' : list(range(10)) })
26332633
assert_frame_equal(result, expected, check_dtype=False)
26342634

2635+
expected = DataFrame([ list(range(10)), list(range(10)) ])
2636+
result = DataFrame([ array.array('i', range(10)), array.array('i',range(10)) ])
2637+
assert_frame_equal(result, expected, check_dtype=False)
2638+
2639+
def test_constructor_iterator(self):
2640+
2641+
expected = DataFrame([ list(range(10)), list(range(10)) ])
2642+
result = DataFrame([ range(10), range(10) ])
2643+
assert_frame_equal(result, expected)
2644+
2645+
def test_constructor_generator(self):
2646+
#related #2305
2647+
2648+
gen1 = (i for i in range(10))
2649+
gen2 = (i for i in range(10))
2650+
2651+
expected = DataFrame([ list(range(10)), list(range(10)) ])
2652+
result = DataFrame([ gen1, gen2 ])
2653+
assert_frame_equal(result, expected)
2654+
2655+
gen = ([ i, 'a'] for i in range(10))
2656+
result = DataFrame(gen)
2657+
expected = DataFrame({ 0 : range(10), 1 : 'a' })
2658+
assert_frame_equal(result, expected)
2659+
26352660
def test_constructor_list_of_dicts(self):
26362661
data = [OrderedDict([['a', 1.5], ['b', 3], ['c', 4], ['d', 6]]),
26372662
OrderedDict([['a', 1.5], ['b', 3], ['d', 6]]),

pandas/tests/test_series.py

+6
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,12 @@ def test_constructor_series(self):
353353

354354
assert_series_equal(s2, s1.sort_index())
355355

356+
def test_constructor_iterator(self):
357+
358+
expected = Series(list(range(10)))
359+
result = Series(range(10))
360+
assert_series_equal(result, expected)
361+
356362
def test_constructor_generator(self):
357363
gen = (i for i in range(10))
358364

0 commit comments

Comments
 (0)