Repository: pandas-dev/pandas

Issue:
BUG: Column indexing does not work in this case
I am using Pandas 0.13.0rc1-23-g286811a, Python 2.7 and Windows XP.

The space in column names is apparently causing a problem. On IPython,

```
df = pd.DataFrame(columns=['a', 'b', 'c c'])
df['d'] = 3
df['c c']
```

Error

```
C:\python_envs\prod2\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key)
   1626             return self._getitem_multilevel(key)
   1627         else:
-> 1628             return self._getitem_column(key)
   1629
   1630     def _getitem_column(self, key):

C:\python_envs\prod2\lib\site-packages\pandas\core\frame.pyc in _getitem_column(self, key)
   1633         # get column
   1634         if self.columns.is_unique:
-> 1635             return self._get_item_cache(key)
   1636
   1637         # duplicate columns & possible reduce dimensionaility

C:\python_envs\prod2\lib\site-packages\pandas\core\generic.pyc in _get_item_cache(self, item)
    977         if res is None:
    978             values = self._data.get(item)
--> 979             res = self._box_item_values(item, values)
    980             cache[item] = res
    981             res._cacher = (item, weakref.ref(self))

C:\python_envs\prod2\lib\site-packages\pandas\core\frame.pyc in _box_item_values(self, key, values)
   1834             return self._constructor(values.T, columns=items, index=self.index)
   1835         else:
-> 1836             return self._box_col_values(values, items)
   1837
   1838     def _box_col_values(self, values, items):

C:\python_envs\prod2\lib\site-packages\pandas\core\frame.pyc in _box_col_values(self, values, items)
   1839         """ provide boxed values for a column """
   1840         return self._constructor_sliced.from_array(values, index=self.index,
-> 1841                                                    name=items, fastpath=True)
   1842
   1843     def __setitem__(self, key, value):

C:\python_envs\prod2\lib\site-packages\pandas\core\series.pyc in from_array(cls, arr, index, name, copy, fastpath)
    233             cls = SparseSeries
    234
--> 235         return cls(arr, index=index, name=name, copy=copy, fastpath=fastpath)
    236
    237     @property

C:\python_envs\prod2\lib\site-packages\pandas\core\series.pyc in __init__(self, data, index, dtype, name, copy, fastpath
)
    130             # data is an ndarray, index is defined
    131             if not isinstance(data, SingleBlockManager):
--> 132                 data = SingleBlockManager(data, index, fastpath=True)
    133             if copy:
    134                 data = data.copy()

C:\python_envs\prod2\lib\site-packages\pandas\core\internals.pyc in __init__(self, block, axis, do_integrity_check, fast
path)
   3413                 block = block[0]
   3414             if not isinstance(block, Block):
-> 3415                 block = make_block(block, axis, axis, ndim=1, fastpath=True)
   3416
   3417         else:

C:\python_envs\prod2\lib\site-packages\pandas\core\internals.pyc in make_block(values, items, ref_items, klass, ndim, dt
ype, fastpath, placement)
   1893
   1894     return klass(values, items, ref_items, ndim=ndim, fastpath=fastpath,
-> 1895                  placement=placement)
   1896
   1897

C:\python_envs\prod2\lib\site-packages\pandas\core\internals.pyc in __init__(self, values, items, ref_items, ndim, fastp
ath, placement)
   1297         super(ObjectBlock, self).__init__(values, items, ref_items, ndim=ndim,
   1298                                           fastpath=fastpath,
-> 1299                                           placement=placement)
   1300
   1301     @property

C:\python_envs\prod2\lib\site-packages\pandas\core\internals.pyc in __init__(self, values, items, ref_items, ndim, fastp
ath, placement)
     63         if len(items) != len(values):
     64             raise ValueError('Wrong number of items passed %d, indices imply '
---> 65                              '%d' % (len(items), len(values)))
     66
     67         self.set_ref_locs(placement)

ValueError: Wrong number of items passed 1, indices imply 0
```



Discussion:

Resolving patch:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1916,6 +1916,11 @@ def _ensure_valid_index(self, value):
                                      'Series')
                 self._data.set_axis(1, value.index.copy(), check_axis=False)
 
+            else:
+                raise ValueError('Cannot set a frame with no defined index '
+                                 'and a value that cannot be converted to a '
+                                 'Series')
+
     def _set_item(self, key, value):
         """
         Add series to DataFrame in specified column.


Test patch:
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -1753,13 +1753,26 @@ def f():
         str(df)
         assert_frame_equal(df,expected)
 
-        # GH5720
+        # GH5720, GH5744
         # don't create rows when empty
         df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
         y = df[df.A > 5]
-        y['New'] = np.nan
-        expected = DataFrame(columns=['A','B','New'])
-        assert_frame_equal(y, expected)
+        def f():
+            y['New'] = np.nan
+        self.assertRaises(ValueError, f)
+
+        df = DataFrame(columns=['a', 'b', 'c c'])
+        def f():
+            df['d'] = 3
+        self.assertRaises(ValueError, f)
+        assert_series_equal(df['c c'],Series(name='c c',dtype=object))
+
+        # reindex columns is ok
+        df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]})
+        y = df[df.A > 5]
+        result = y.reindex(columns=['A','B','C'])
+        expected = DataFrame(columns=['A','B','C'])
+        assert_frame_equal(result,expected)
 
     def test_cache_updating(self):
         # GH 4939, make sure to update the cache on setitem