Skip to content

Commit f8b6208

Browse files
committed
Merge pull request #5745 from jreback/empty_frame2
BUG: don't allow an empty dataframe to have scalar assignment succeed (GH5744)
2 parents cfcade2 + c24f2d0 commit f8b6208

File tree

3 files changed

+23
-5
lines changed

3 files changed

+23
-5
lines changed

doc/source/release.rst

+1-1
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

+5
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

+17-4
Original file line numberDiff line numberDiff line change
@@ -1774,13 +1774,26 @@ def f():
17741774
str(df)
17751775
assert_frame_equal(df,expected)
17761776

1777-
# GH5720
1777+
# GH5720, GH5744
17781778
# don't create rows when empty
17791779
df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
17801780
y = df[df.A > 5]
1781-
y['New'] = np.nan
1782-
expected = DataFrame(columns=['A','B','New'])
1783-
assert_frame_equal(y, expected)
1781+
def f():
1782+
y['New'] = np.nan
1783+
self.assertRaises(ValueError, f)
1784+
1785+
df = DataFrame(columns=['a', 'b', 'c c'])
1786+
def f():
1787+
df['d'] = 3
1788+
self.assertRaises(ValueError, f)
1789+
assert_series_equal(df['c c'],Series(name='c c',dtype=object))
1790+
1791+
# reindex columns is ok
1792+
df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
1793+
y = df[df.A > 5]
1794+
result = y.reindex(columns=['A','B','C'])
1795+
expected = DataFrame(columns=['A','B','C'])
1796+
assert_frame_equal(result,expected)
17841797

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

0 commit comments

Comments
 (0)