-
-
Notifications
You must be signed in to change notification settings - Fork 18.3k
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
Changes from all commits
3220c80
803e60e
c72240c
69a6aad
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -324,8 +324,8 @@ def length_of_indexer(indexer, target=None) -> int: | |
start, stop = stop + 1, start + 1 | ||
step = -step | ||
return (stop - start + step - 1) // step | ||
elif isinstance(indexer, (ABCSeries, ABCIndex, np.ndarray, list)): | ||
if isinstance(indexer, list): | ||
elif isinstance(indexer, (ABCSeries, ABCIndex, np.ndarray, list, range)): | ||
if isinstance(indexer, (list, range)): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the range case can be implemented separately + more efficiently, similar to the slice case There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You mean that a range object should have been converted to a slice before calling At the moment it's simply the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ah, but it's probably because of calling There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i was just thinking There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. does this not work? |
||
indexer = np.array(indexer) | ||
|
||
if indexer.dtype == bool: | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
@@ -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 | ||
|
@@ -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") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, | ||
|
@@ -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): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. annotate |
||
""" | ||
|
||
Parameters | ||
|
@@ -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) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
|
@@ -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: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
incorrect |
||
): | ||
value = np.datetime64("NaT", "ns") | ||
|
||
arr[indexer] = value | ||
|
||
def putmask(self, mask, new, align: bool = True): | ||
|
||
|
@@ -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()) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: | ||
|
@@ -625,7 +642,14 @@ def fast_xs(self, loc: int) -> ArrayLike: | |
else: | ||
temp_dtype = dtype | ||
|
||
result = np.array([arr[loc] for arr in self.arrays], dtype=temp_dtype) | ||
if dtype == "object": | ||
# TODO properly test this, check | ||
# pandas/tests/indexing/test_chaining_and_caching.py::TestChaining | ||
# ::test_chained_getitem_with_lists | ||
result = np.empty(self.shape_proper[1], dtype=dtype) | ||
result[:] = [arr[loc] for arr in self.arrays] | ||
else: | ||
result = np.array([arr[loc] for arr in self.arrays], dtype=temp_dtype) | ||
if isinstance(dtype, ExtensionDtype): | ||
result = dtype.construct_array_type()._from_sequence(result, dtype=dtype) | ||
return result | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why is this desired behavior? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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): | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can the decorator be used for this?