Skip to content

Commit 91d1aa0

Browse files
committed
Raise ValueError when settings scalars with no index
1 parent d43aba8 commit 91d1aa0

File tree

3 files changed

+16
-5
lines changed

3 files changed

+16
-5
lines changed

doc/source/whatsnew/v0.21.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,7 @@ Other API Changes
461461
- :class:`Period` is now immutable, and will now raise an ``AttributeError`` when a user tries to assign a new value to the ``ordinal`` or ``freq`` attributes (:issue:`17116`).
462462
- :func:`to_datetime` when passed a tz-aware ``origin=`` kwarg will now raise a more informative ``ValueError`` rather than a ``TypeError`` (:issue:`16842`)
463463
- Renamed non-functional ``index`` to ``index_col`` in :func:`read_stata` to improve API consistency (:issue:`16342`)
464+
- Setting on a column with a scalar value and no index now raises a ``ValueError`` (:issue:`16823`)
464465

465466

466467
.. _whatsnew_0210.deprecations:

pandas/core/frame.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -2499,17 +2499,22 @@ def _ensure_valid_index(self, value):
24992499
passed value
25002500
"""
25012501
# GH5632, make sure that we are a Series convertible
2502-
if not len(self.index) and is_list_like(value):
2502+
if not len(self.index):
2503+
if not is_list_like(value):
2504+
# GH16823, Raise an error due to loss of information
2505+
raise ValueError('If using all scalar values, you must pass'
2506+
' an index')
25032507
try:
25042508
value = Series(value)
25052509
except:
2506-
raise ValueError('Cannot set a frame with no defined index '
2507-
'and a value that cannot be converted to a '
2508-
'Series')
2509-
2510+
raise ValueError('Cannot set a frame with no defined'
2511+
'index and a value that cannot be '
2512+
'converted to a Series')
2513+
25102514
self._data = self._data.reindex_axis(value.index.copy(), axis=1,
25112515
fill_value=np.nan)
25122516

2517+
25132518
def _set_item(self, key, value):
25142519
"""
25152520
Add series to DataFrame in specified column.

pandas/tests/frame/test_indexing.py

+5
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,11 @@ def test_setitem_empty_frame_with_boolean(self):
721721
df[df > df2] = 47
722722
assert_frame_equal(df, df2)
723723

724+
def test_setitem_scalars_no_index(self):
725+
# GH16823
726+
df = DataFrame()
727+
pytest.raises(ValueError, df.__setitem__, 'foo', 1)
728+
724729
def test_getitem_empty_frame_with_boolean(self):
725730
# Test for issue #11859
726731

0 commit comments

Comments
 (0)