diff --git a/doc/source/release.rst b/doc/source/release.rst index f121928c06f72..96004737c4d0f 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -246,7 +246,7 @@ API Changes (:issue:`4390`) - allow ``ix/loc`` for Series/DataFrame/Panel to set on any axis even when the single-key is not currently contained in the index for that axis - (:issue:`2578`, :issue:`5226`) + (:issue:`2578`, :issue:`5226`, :issue:`5632`) - Default export for ``to_clipboard`` is now csv with a sep of `\t` for compat (:issue:`3368`) - ``at`` now will enlarge the object inplace (and return the same) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 6ef6d8c75216f..5e31b14fa7bd3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1895,9 +1895,16 @@ def _ensure_valid_index(self, value): passed value """ if not len(self.index): + + # GH5632, make sure that we are a Series convertible + try: + value = Series(value) + except: + pass + if not isinstance(value, Series): raise ValueError('Cannot set a frame with no defined index ' - 'and a non-series') + 'and a value that cannot be converted to a Series') self._data.set_axis(1, value.index.copy(), check_axis=False) def _set_item(self, key, value): diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 44160609235df..7b05a0b78b121 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1635,6 +1635,42 @@ def f(): df.loc[:,1] = 1 self.assertRaises(ValueError, f) + # these work as they don't really change + # anything but the index + # GH5632 + expected = DataFrame(columns=['foo']) + def f(): + df = DataFrame() + df['foo'] = Series([]) + return df + assert_frame_equal(f(), expected) + def f(): + df = DataFrame() + df['foo'] = Series(df.index) + return df + assert_frame_equal(f(), expected) + def f(): + df = DataFrame() + df['foo'] = Series(range(len(df))) + return df + assert_frame_equal(f(), expected) + def f(): + df = DataFrame() + df['foo'] = [] + return df + assert_frame_equal(f(), expected) + def f(): + df = DataFrame() + df['foo'] = df.index + return df + assert_frame_equal(f(), expected) + def f(): + df = DataFrame() + df['foo'] = range(len(df)) + return df + assert_frame_equal(f(), expected) + + df = DataFrame() df2 = DataFrame() df2[1] = Series([1],index=['foo']) df.loc[:,1] = Series([1],index=['foo'])