Repository: pandas-dev/pandas

Issue:
Assignments: numerics, strings and .loc
Why would assigning an entire column to an array of values work differently with numbers vs strings?

**Assigning numeric values:**

``` python
>>> df = pd.DataFrame(columns=['x', 'y'])
>>> df['x'] = [1, 2]
>>> df
   x    y
0  1  NaN
1  2  NaN
```

**Assigning string values:**

``` python
>>> df = pd.DataFrame(columns=['x', 'y'])
>>> df['x'] = ['1', '2']
ValueError: could not broadcast input array from shape (2) into shape (0)
```

Btw according to latest docs `.loc` can append, but can it append more than one value at once?

**Setting multiple via `.loc`:**

``` python
>>> df = pd.DataFrame(columns=['x', 'y'])
>>> df.loc[:, 'x'] = [1, 2]
>>> df
Empty DataFrame
Columns: [x, y]
Index: []
>>> df.loc[[0, 1], 'x'] = [1, 2]
>>> df
Empty DataFrame
Columns: [x, y]
Index: []
>>> df.loc[0:2, 'x'] = [1, 2]
>>> df
Empty DataFrame
Columns: [x, y]
Index: []
```

**Setting single via `.loc`:** (this works ofc)

``` python
>>> df = pd.DataFrame(columns=['x', 'y'])
>>> df.loc[0, 'x'] = 1
>>> df
   x    y
0  1  NaN
```



Discussion:
This is not valid python code (what you pasted)

```
>>> df = pd.DataFrame(columns='x', 'y')
SyntaxError: non-keyword arg after keyword arg

```

Presumably missing square brackets.

Yea I retyped it manually, a typo.

can you fix the examples pls

Fixed typos, should work now; sry had to type it manually.

Huh, more weird stuff, check this out:

``` python
>>> df = pd.DataFrame(columns=['x', 'y'])
>>> df.x = [1, 2]  # no error?
>>> df.y  # expect [nan, nan]?
ValueError: Wrong number of items passed 2, indices imply 0
```

Btw: this is v0.13.0, not the head rev; not sure if it has been addressed or not already but I skimmed through recent changes/issues and haven't found anything related.

assigning to columns via setattr is currently an open issue (should this actually error), hard to say, see here: https://github.com/pydata/pandas/issues/5904

@jreback Still crashes with `__setitem__` as well.

@aldanor what are you refurring to: `Still crashes with __setitem__ as well.`


Resolving patch:
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -1421,7 +1421,18 @@ def set(self, item, value, check=False):
                     return
             except:
                 pass
-        self.values[loc] = value
+        try:
+            self.values[loc] = value
+        except (ValueError):
+
+            # broadcasting error
+            # see GH6171
+            new_shape = list(value.shape)
+            new_shape[0] = len(self.items)
+            self.values = np.empty(tuple(new_shape),dtype=self.dtype)
+            self.values.fill(np.nan)
+            self.values[loc] = value
+
 
     def _maybe_downcast(self, blocks, downcast=None):
 


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
@@ -1987,6 +1987,23 @@ def f():
         expected = DataFrame(0,index=[0],columns=['a'])
         assert_frame_equal(df, expected)
 
+        # GH 6171
+        # consistency on empty frames
+        df = DataFrame(columns=['x', 'y'])
+        df['x'] = [1, 2]
+        expected = DataFrame(dict(x = [1,2], y = [np.nan,np.nan]))
+        assert_frame_equal(df, expected, check_dtype=False)
+
+        df = DataFrame(columns=['x', 'y'])
+        df['x'] = ['1', '2']
+        expected = DataFrame(dict(x = ['1','2'], y = [np.nan,np.nan]),dtype=object)
+        assert_frame_equal(df, expected)
+
+        df = DataFrame(columns=['x', 'y'])
+        df.loc[0, 'x'] = 1
+        expected = DataFrame(dict(x = [1], y = [np.nan]))
+        assert_frame_equal(df, expected, check_dtype=False)
+
     def test_cache_updating(self):
         # GH 4939, make sure to update the cache on setitem