Skip to content

BUG: assignment to multiple columns when some column do not exist #29334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 14, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,35 @@ Indexing
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` when indexing with an integer key on a object-dtype :class:`Index` that is not all-integers (:issue:`31905`)
-

Assignment to multiple columns of a DataFrame when some columns do not exist
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move this to the section where we od api-breaking changes.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Assignment to multiple columns of a :class:`DataFrame` when some of the columns do not exist would previously assign the values to the last column. Now, new columns would be constructed with the right values. (:issue:`13658`)

.. ipython:: python

df = pd.DataFrame({'a': [0, 1, 2], 'b': [3, 4, 5]})
df

*Previous behavior*:

.. code-block:: ipython

In [3]: df[['a', 'c']] = 1
In [4]: df
Out[4]:
a b
0 1 1
1 1 1
2 1 1

*New behavior*:

.. ipython:: python

df[['a', 'c']] = 1
df

Missing
^^^^^^^

Expand Down
1 change: 1 addition & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2685,6 +2685,7 @@ def _setitem_array(self, key, value):
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
else:
self.loc._ensure_listlike_indexer(key, axis=1)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it looks like you're also calling this inside _get_setitem_indexer; do you need to also call it here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_get_setitem_indexer is not called in this code path

indexer = self.loc._get_listlike_indexer(
key, axis=1, raise_missing=False
)[1]
Expand Down
40 changes: 40 additions & 0 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pandas.util._decorators import Appender

from pandas.core.dtypes.common import (
is_hashable,
is_integer,
is_iterator,
is_list_like,
Expand Down Expand Up @@ -581,6 +582,9 @@ def _get_setitem_indexer(self, key):
"""
Convert a potentially-label-based key into a positional indexer.
"""
if self.name == "loc":
self._ensure_listlike_indexer(key)

if self.axis is not None:
return self._convert_tuple(key, is_setter=True)

Expand Down Expand Up @@ -611,6 +615,42 @@ def _get_setitem_indexer(self, key):
raise
raise IndexingError(key) from e

def _ensure_listlike_indexer(self, key, axis=None):
"""
Ensure that a list-like of column labels are all present by adding them if
they do not already exist.

Parameters
----------
key : _LocIndexer key or list-like of column labels
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i dont think key being a _LocIndexer object makes sense

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why? _ensure_listlike_indexer is called at

self._ensure_listlike_indexer(key)

Target labels.
axis : key axis if known
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it looks like axis isnt used here, is it necessary?

Copy link
Contributor Author

@howsiwei howsiwei Mar 6, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's used at

axis == column_axis

For rationale of coding this way, see #29334 (comment).

"""
column_axis = 1

# column only exists in 2-dimensional DataFrame
if self.ndim != 2:
return

if isinstance(key, tuple):
# key may be a tuple if key is a _LocIndexer key
# in that case, set key to the column part of key
key = key[column_axis]
axis = column_axis

if (
axis == column_axis
and not isinstance(self.obj._get_axis(column_axis), ABCMultiIndex)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self.obj._get_axis(column_axis) --> self.obj.columns

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, changed

and is_list_like_indexer(key)
and not com.is_bool_indexer(key)
and all(is_hashable(k) for k in key)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think the hashable check you can skip and the calls below will take care of it

Copy link
Contributor Author

@howsiwei howsiwei Mar 6, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If no hashable check is performed here, some test cases fail , eg.

def test_setitem_ndarray_3d(self, index, obj, idxr, idxr_id):
because different errors are raised compared to the original code when some keys are not hashable.

):
for k in key:
try:
self.obj[k]
except KeyError:
self.obj[k] = np.nan

def __setitem__(self, key, value):
if isinstance(key, tuple):
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
Expand Down
64 changes: 57 additions & 7 deletions pandas/tests/frame/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,63 @@ def test_setitem_list_of_tuples(self, float_frame):
expected = Series(tuples, index=float_frame.index, name="tuples")
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize(
"columns,box,expected",
[
(
["A", "B", "C", "D"],
7,
pd.DataFrame(
[[7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7]],
columns=["A", "B", "C", "D"],
),
),
(
["C", "D"],
[7, 8],
pd.DataFrame(
[[1, 2, 7, 8], [3, 4, 7, 8], [5, 6, 7, 8]],
columns=["A", "B", "C", "D"],
),
),
(
["A", "B", "C"],
np.array([7, 8, 9], dtype=np.int64),
pd.DataFrame(
[[7, 8, 9], [7, 8, 9], [7, 8, 9]], columns=["A", "B", "C"]
),
),
(
["B", "C", "D"],
[[7, 8, 9], [10, 11, 12], [13, 14, 15]],
pd.DataFrame(
[[1, 7, 8, 9], [3, 10, 11, 12], [5, 13, 14, 15]],
columns=["A", "B", "C", "D"],
),
),
(
["C", "A", "D"],
np.array([[7, 8, 9], [10, 11, 12], [13, 14, 15]], dtype=np.int64),
pd.DataFrame(
[[8, 2, 7, 9], [11, 4, 10, 12], [14, 6, 13, 15]],
columns=["A", "B", "C", "D"],
),
),
(
["A", "C"],
pd.DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]),
pd.DataFrame(
[[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"]
),
),
],
)
def test_setitem_list_missing_columns(self, columns, box, expected):
# GH 29334
df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"])
df[columns] = box
tm.assert_frame_equal(df, expected)

def test_setitem_multi_index(self):
# GH7655, test that assigning to a sub-frame of a frame
# with multi-index columns aligns both rows and columns
Expand Down Expand Up @@ -459,13 +516,6 @@ def test_setitem(self, float_frame):
float_frame["col6"] = series
tm.assert_series_equal(series, float_frame["col6"], check_names=False)

msg = (
r"\"None of \[Float64Index\(\[.*dtype='float64'\)\] are in the "
r"\[columns\]\""
)
with pytest.raises(KeyError, match=msg):
float_frame[np.random.randn(len(float_frame) + 1)] = 1

# set ndarray
arr = np.random.randn(len(float_frame))
float_frame["col9"] = arr
Expand Down
58 changes: 58 additions & 0 deletions pandas/tests/indexing/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,64 @@ def test_loc_setitem_with_scalar_index(self, indexer, value):

assert is_scalar(result) and result == "Z"

@pytest.mark.parametrize(
"index,box,expected",
[
(
([0, 2], ["A", "B", "C", "D"]),
7,
pd.DataFrame(
[[7, 7, 7, 7], [3, 4, np.nan, np.nan], [7, 7, 7, 7]],
columns=["A", "B", "C", "D"],
),
),
(
(1, ["C", "D"]),
[7, 8],
pd.DataFrame(
[[1, 2, np.nan, np.nan], [3, 4, 7, 8], [5, 6, np.nan, np.nan]],
columns=["A", "B", "C", "D"],
),
),
(
(1, ["A", "B", "C"]),
np.array([7, 8, 9], dtype=np.int64),
pd.DataFrame(
[[1, 2, np.nan], [7, 8, 9], [5, 6, np.nan]],
columns=["A", "B", "C"],
),
),
(
(slice(1, 3, None), ["B", "C", "D"]),
[[7, 8, 9], [10, 11, 12]],
pd.DataFrame(
[[1, 2, np.nan, np.nan], [3, 7, 8, 9], [5, 10, 11, 12]],
columns=["A", "B", "C", "D"],
),
),
(
(slice(1, 3, None), ["C", "A", "D"]),
np.array([[7, 8, 9], [10, 11, 12]], dtype=np.int64),
pd.DataFrame(
[[1, 2, np.nan, np.nan], [8, 4, 7, 9], [11, 6, 10, 12]],
columns=["A", "B", "C", "D"],
),
),
(
(slice(None, None, None), ["A", "C"]),
pd.DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]),
pd.DataFrame(
[[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"]
),
),
],
)
def test_loc_setitem_missing_columns(self, index, box, expected):
# GH 29334
df = pd.DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"])
df.loc[index] = box
tm.assert_frame_equal(df, expected)

def test_loc_coercion(self):

# 12411
Expand Down