Skip to content

Commit c24f2d0

Browse files
committed
BUG: don't allow an empty dataframe to have scalar assignment succeed (GH5744)
1 parent bac7c6e commit c24f2d0

File tree

3 files changed

+23
-5
lines changed

3 files changed

+23
-5
lines changed

doc/source/release.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ API Changes
247247
(:issue:`4390`)
248248
- allow ``ix/loc`` for Series/DataFrame/Panel to set on any axis even when
249249
the single-key is not currently contained in the index for that axis
250-
(:issue:`2578`, :issue:`5226`, :issue:`5632`, :issue:`5720`)
250+
(:issue:`2578`, :issue:`5226`, :issue:`5632`, :issue:`5720`, :issue:`5744`)
251251
- Default export for ``to_clipboard`` is now csv with a sep of `\t` for
252252
compat (:issue:`3368`)
253253
- ``at`` now will enlarge the object inplace (and return the same)

pandas/core/frame.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1916,6 +1916,11 @@ def _ensure_valid_index(self, value):
19161916
'Series')
19171917
self._data.set_axis(1, value.index.copy(), check_axis=False)
19181918

1919+
else:
1920+
raise ValueError('Cannot set a frame with no defined index '
1921+
'and a value that cannot be converted to a '
1922+
'Series')
1923+
19191924
def _set_item(self, key, value):
19201925
"""
19211926
Add series to DataFrame in specified column.

pandas/tests/test_indexing.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1753,13 +1753,26 @@ def f():
17531753
str(df)
17541754
assert_frame_equal(df,expected)
17551755

1756-
# GH5720
1756+
# GH5720, GH5744
17571757
# don't create rows when empty
17581758
df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
17591759
y = df[df.A > 5]
1760-
y['New'] = np.nan
1761-
expected = DataFrame(columns=['A','B','New'])
1762-
assert_frame_equal(y, expected)
1760+
def f():
1761+
y['New'] = np.nan
1762+
self.assertRaises(ValueError, f)
1763+
1764+
df = DataFrame(columns=['a', 'b', 'c c'])
1765+
def f():
1766+
df['d'] = 3
1767+
self.assertRaises(ValueError, f)
1768+
assert_series_equal(df['c c'],Series(name='c c',dtype=object))
1769+
1770+
# reindex columns is ok
1771+
df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
1772+
y = df[df.A > 5]
1773+
result = y.reindex(columns=['A','B','C'])
1774+
expected = DataFrame(columns=['A','B','C'])
1775+
assert_frame_equal(result,expected)
17631776

17641777
def test_cache_updating(self):
17651778
# GH 4939, make sure to update the cache on setitem

0 commit comments

Comments
 (0)