Skip to content

BUG: constructing a DataFrame using range doesn't work #26343

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,7 @@ Reshaping
- Bug in :func:`pivot_table` where columns with ``NaN`` values are dropped even if ``dropna`` argument is ``False``, when the ``aggfunc`` argument contains a ``list`` (:issue:`22159`)
- Bug in :func:`concat` where the resulting ``freq`` of two :class:`DatetimeIndex` with the same ``freq`` would be dropped (:issue:`3232`).
- Bug in :func:`merge` where merging with equivalent Categorical dtypes was raising an error (:issue:`22501`)
- bug in :class:`DataFrame` instantiating with a ``range`` (e.g. ``pd.DataFrame(range(3))``) raised an error (:issue:`26342`).
- Bug in :class:`DataFrame` constructor when passing non-empty tuples would cause a segmentation fault (:issue:`25691`)
- Bug in :func:`pandas.cut` where large bins could incorrectly raise an error due to an integer overflow (:issue:`26045`)
- Bug in :func:`DataFrame.sort_index` where an error is thrown when a multi-indexed DataFrame is sorted on all levels with the initial level sorted last (:issue:`26053`)
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@
def maybe_convert_platform(values):
""" try to do platform conversion, allow ndarray or list here """

if isinstance(values, (list, tuple)):
values = construct_1d_object_array_from_listlike(list(values))
if isinstance(values, (list, tuple, range)):
values = construct_1d_object_array_from_listlike(values)
if getattr(values, 'dtype', None) == np.object_:
if hasattr(values, '_values'):
values = values._values
Expand Down
28 changes: 25 additions & 3 deletions pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,13 @@ class TestDataFrameConstructors(TestData):
lambda: DataFrame(()),
lambda: DataFrame([]),
lambda: DataFrame((x for x in [])),
lambda: DataFrame(range(0)),
lambda: DataFrame(data=None),
lambda: DataFrame(data={}),
lambda: DataFrame(data=()),
lambda: DataFrame(data=[]),
lambda: DataFrame(data=(x for x in []))
lambda: DataFrame(data=(x for x in [])),
lambda: DataFrame(data=range(0)),
])
def test_empty_constructor(self, constructor):
expected = DataFrame()
Expand Down Expand Up @@ -999,6 +1001,17 @@ def __len__(self, n):
array.array('i', range(10))])
tm.assert_frame_equal(result, expected, check_dtype=False)

def test_constructor_range(self):
# GH26342
result = DataFrame(range(10))
expected = DataFrame(list(range(10)))
tm.assert_frame_equal(result, expected)

def test_constructor_list_of_ranges(self):
result = DataFrame([range(10), range(10)])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would reference the issue as a comment above this line as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, this is just an existing test that has been moved. It already passed before this PR.

expected = DataFrame([list(range(10)), list(range(10))])
tm.assert_frame_equal(result, expected)

def test_constructor_iterable(self):
# GH 21987
class Iter:
Expand All @@ -1011,9 +1024,13 @@ def __iter__(self):
tm.assert_frame_equal(result, expected)

def test_constructor_iterator(self):
result = DataFrame(iter(range(10)))
expected = DataFrame(list(range(10)))
tm.assert_frame_equal(result, expected)

def test_constructor_list_of_iterators(self):
result = DataFrame([iter(range(10)), iter(range(10))])
expected = DataFrame([list(range(10)), list(range(10))])
result = DataFrame([range(10), range(10)])
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A plain range isn't a iterator, so this fixes up the nomenclature.

The range case is now placed in test_constructor_list_of_ranges, which is clearer.

tm.assert_frame_equal(result, expected)

def test_constructor_generator(self):
Expand Down Expand Up @@ -2251,8 +2268,13 @@ def test_to_frame_with_falsey_names(self):

@pytest.mark.parametrize('dtype', [None, 'uint8', 'category'])
def test_constructor_range_dtype(self, dtype):
# GH 16804
expected = DataFrame({'A': [0, 1, 2, 3, 4]}, dtype=dtype or 'int64')

# GH 26342
result = DataFrame(range(5), columns=['A'], dtype=dtype)
tm.assert_frame_equal(result, expected)

# GH 16804
result = DataFrame({'A': range(5)}, dtype=dtype)
tm.assert_frame_equal(result, expected)

Expand Down