Skip to content
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

WIP [ArrayManager] API: setitem to set new columns / loc+iloc to update inplace #39578

Closed
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,4 @@ jobs:
run: |
source activate pandas-dev
pytest pandas/tests/frame/methods --array-manager
pytest pandas/tests/frame/indexing --array-manager
8 changes: 7 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,10 @@ def _as_manager(self, typ: str) -> DataFrame:
# fastpath of passing a manager doesn't check the option/manager class
return DataFrame(new_mgr)

@property
def _has_array_manager(self):
return isinstance(self._mgr, ArrayManager)

# ----------------------------------------------------------------------

@property
Expand Down Expand Up @@ -3240,7 +3244,9 @@ def _setitem_array(self, key, value):
key, axis=1, raise_missing=False
)[1]
self._check_setitem_copy()
self.iloc[:, indexer] = value
self.iloc._setitem_with_indexer(
(slice(None), indexer), value, name="setitem"
)

def _setitem_frame(self, key, value):
# support boolean setting with DataFrame input, e.g.
Expand Down
17 changes: 13 additions & 4 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1684,7 +1684,9 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str):

elif len(ilocs) == 1 and lplane_indexer == len(value) and not is_scalar(pi):
# We are setting multiple rows in a single column.
self._setitem_single_column(ilocs[0], value, pi)
self._setitem_single_column(
ilocs[0], value, pi, overwrite=name == "setitem"
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 we ever get name=="setitem" ATM, maybe update the docstring to describe what this indicates?

)

elif len(ilocs) == 1 and 0 != lplane_indexer != len(value):
# We are trying to set N values into M entries of a single
Expand All @@ -1708,7 +1710,7 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str):
elif len(ilocs) == len(value):
# We are setting multiple columns in a single row.
for loc, v in zip(ilocs, value):
self._setitem_single_column(loc, v, pi)
self._setitem_single_column(loc, v, pi, overwrite=name == "setitem")

elif len(ilocs) == 1 and com.is_null_slice(pi) and len(self.obj) == 0:
# This is a setitem-with-expansion, see
Expand All @@ -1728,7 +1730,7 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str):

# scalar value
for loc in ilocs:
self._setitem_single_column(loc, value, pi)
self._setitem_single_column(loc, value, pi, overwrite=name == "setitem")
Copy link
Member

Choose a reason for hiding this comment

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

maybe define overwrite once earlier on?


def _setitem_with_indexer_2d_value(self, indexer, value):
# We get here with np.ndim(value) == 2, excluding DataFrame,
Expand Down Expand Up @@ -1797,7 +1799,7 @@ def _setitem_with_indexer_frame_value(self, indexer, value: DataFrame, name: str

self._setitem_single_column(loc, val, pi)

def _setitem_single_column(self, loc: int, value, plane_indexer):
def _setitem_single_column(self, loc: int, value, plane_indexer, overwrite=True):
Copy link
Member

Choose a reason for hiding this comment

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

annotate

"""

Parameters
Expand All @@ -1806,7 +1808,14 @@ def _setitem_single_column(self, loc: int, value, plane_indexer):
Indexer for column position
plane_indexer : int, slice, listlike[int]
The indexer we use for setitem along axis=0.
overwrite : bool
Whether to overwrite the original column, or update the existing
column inplace
"""
if not overwrite and self.obj._has_array_manager:
self.obj._mgr.setitem(plane_indexer, value, loc)
return

pi = plane_indexer

ser = self.obj._ixs(loc, axis=1)
Expand Down
25 changes: 21 additions & 4 deletions pandas/core/internals/array_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
from pandas.core.dtypes.cast import find_common_type, infer_dtype_from_scalar
from pandas.core.dtypes.common import (
is_bool_dtype,
is_datetime64_dtype,
is_dtype_equal,
is_extension_array_dtype,
is_numeric_dtype,
is_scalar,
)
from pandas.core.dtypes.dtypes import ExtensionDtype, PandasDtype
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
Expand Down Expand Up @@ -339,9 +341,24 @@ def where(self, other, cond, align: bool, errors: str, axis: int) -> ArrayManage
axis=axis,
)

# TODO what is this used for?
# def setitem(self, indexer, value) -> ArrayManager:
# return self.apply_with_block("setitem", indexer=indexer, value=value)
def setitem(self, indexer, value, column_idx) -> ArrayManager:
Copy link
Member

Choose a reason for hiding this comment

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

Block.setitem isn't always inplace, its a try-inplace-fallback-to-cast

Copy link
Member Author

@jorisvandenbossche jorisvandenbossche Feb 3, 2021

Choose a reason for hiding this comment

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

Yep, but not in ArrayManager (I know I need to open an issue about that to discuss this in general -> #39584)

"""
Set value for a single column and a given row indexer. For example, from
``df.loc[indexer] = value``
"""
arr = self.arrays[column_idx]

# TODO this special case can be removed once we only store EAs
# special case to support setting np.nan in a non-float numpy array
if (
isinstance(arr, np.ndarray)
and is_datetime64_dtype(arr.dtype)
and is_scalar(value)
and isna(value)
Copy link
Member

Choose a reason for hiding this comment

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

pls use is_valid_nat_for_dtype, otherwise this will incorrectly let through td64 nat

(i know i know, this is just draft and youre not looking for comments like this, but this could easily fall through the cracks)

Copy link
Member Author

Choose a reason for hiding this comment

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

No, this is certainly a comment that is useful ;) (I was actually planning to comment on this and ask you, because I already realized the same would need to be done for timedelta, that just didn't occur in the tests)

Copy link
Member Author

Choose a reason for hiding this comment

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

Actually, in this case we explicitly want to include np.nan (which I think is_valid_nat_for_dtype doesn't do?), since we allow setting np.nan or None in a datetime column, but a datetime64[ns] numpy array doesn't allow this (and the same for timedelta64)

Copy link
Member

Choose a reason for hiding this comment

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

which I think is_valid_nat_for_dtype doesn't do?

incorrect

):
value = np.datetime64("NaT", "ns")

arr[indexer] = value

def putmask(self, mask, new, align: bool = True):

Expand Down Expand Up @@ -454,7 +471,7 @@ def is_mixed_type(self) -> bool:

@property
def is_numeric_mixed_type(self) -> bool:
return False
return all(is_numeric_dtype(t) for t in self.get_dtypes())
Copy link
Member

Choose a reason for hiding this comment

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

should the "mixed" be meaningful here, i.e. what if we're homogeneous dtype?

Copy link
Member Author

Choose a reason for hiding this comment

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

Then it will also return True, like it does for BlockManager (this basically only wants to know that all columns are numeric, while not necessarily being all the same dtype)


@property
def any_extension_types(self) -> bool:
Expand Down
21 changes: 15 additions & 6 deletions pandas/tests/frame/indexing/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,23 +243,32 @@ def test_setitem_mask_categorical(self, exp_multi_row):
# category c is kept in .categories
tm.assert_frame_equal(df, exp_fancy)

def test_loc_setitem_categorical_values_partial_column_slice(self):
def test_loc_setitem_categorical_values_partial_column_slice(
self, using_array_manager
):
# Assigning a Category to parts of a int/... column uses the values of
# the Categorical
df = DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")})
exp = DataFrame({"a": [1, "b", "b", 1, 1], "b": list("aabba")})
df.loc[1:2, "a"] = Categorical(["b", "b"], categories=["a", "b"])
df.loc[2:3, "b"] = Categorical(["b", "b"], categories=["a", "b"])
tm.assert_frame_equal(df, exp)

def test_loc_setitem_single_row_categorical(self):
if using_array_manager:
Copy link
Member

Choose a reason for hiding this comment

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

why is this desired behavior?

Copy link
Member Author

Choose a reason for hiding this comment

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

Pending outcome of the discussion in #39584, the "a" column has integer dtype and should preserve that, so string categorical cannot be set

with pytest.raises(ValueError, match=""):
df.loc[1:2, "a"] = Categorical(["b", "b"], categories=["a", "b"])
else:
df.loc[1:2, "a"] = Categorical(["b", "b"], categories=["a", "b"])
df.loc[2:3, "b"] = Categorical(["b", "b"], categories=["a", "b"])
tm.assert_frame_equal(df, exp)

def test_loc_setitem_single_row_categorical(self, using_array_manager):
# GH 25495
df = DataFrame({"Alpha": ["a"], "Numeric": [0]})
categories = Categorical(df["Alpha"], categories=["a", "b", "c"])
df.loc[:, "Alpha"] = categories

result = df["Alpha"]
expected = Series(categories, index=df.index, name="Alpha")
if using_array_manager:
# with ArrayManager the object dtype is preserved
expected = expected.astype(object)
tm.assert_series_equal(result, expected)

def test_loc_indexing_preserves_index_category_dtype(self):
Expand Down
Loading