Skip to content

PERF: setting values via df.loc / df.iloc with pyarrow-backed columns #50248

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 8 commits into from
Dec 17, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 3 additions & 0 deletions asv_bench/benchmarks/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,8 @@ def time_setitem_list(self, multiple_chunks):
def time_setitem_slice(self, multiple_chunks):
self.array[::10] = "foo"

def time_setitem_null_slice(self, multiple_chunks):
self.array[:] = "foo"

def time_tolist(self, multiple_chunks):
self.array.tolist()
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,7 @@ Performance improvements
- Reduce memory usage of :meth:`DataFrame.to_pickle`/:meth:`Series.to_pickle` when using BZ2 or LZMA (:issue:`49068`)
- Performance improvement for :class:`~arrays.StringArray` constructor passing a numpy array with type ``np.str_`` (:issue:`49109`)
- Performance improvement in :meth:`~arrays.ArrowExtensionArray.factorize` (:issue:`49177`)
- Performance improvement in :meth:`~arrays.ArrowExtensionArray.__setitem__` when key is a null slice (:issue:`50248`)
- Performance improvement in :meth:`DataFrame.join` when joining on a subset of a :class:`MultiIndex` (:issue:`48611`)
- Performance improvement for :meth:`MultiIndex.intersection` (:issue:`48604`)
- Performance improvement in ``var`` for nullable dtypes (:issue:`48379`).
Expand Down
25 changes: 24 additions & 1 deletion pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

from pandas.core.arraylike import OpsMixin
from pandas.core.arrays.base import ExtensionArray
import pandas.core.common as com
from pandas.core.indexers import (
check_array_indexer,
unpack_tuple_and_ellipses,
Expand Down Expand Up @@ -897,9 +898,31 @@ def __setitem__(self, key: int | slice | np.ndarray, value: Any) -> None:
None
"""
key = check_array_indexer(self, key)
indices = self._indexing_key_to_indices(key)
value = self._maybe_convert_setitem_value(value)

# fast path (GH50248)
if com.is_null_slice(key):
if is_scalar(value) and not pa_version_under6p0:
Copy link
Member

Choose a reason for hiding this comment

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

Do we need to directly check not pa_version_under6p0? If a user has data with a pyarrow data type I think it's implicitly assumed that pyarrow is installed?

Copy link
Member Author

Choose a reason for hiding this comment

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

that path hits pc.if_else which I believe was added in 6.0. pc.if_else was the fastest way I found to create an array of all the same value. There are slower options of course.

Copy link
Member

Choose a reason for hiding this comment

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

We recently bumped the min pyarrow version to 6.0 so I think this should be safe to remove

Copy link
Member Author

Choose a reason for hiding this comment

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

done

fill_value = pa.scalar(value, type=self._data.type, from_pandas=True)
try:
self._data = pc.if_else(True, fill_value, self._data)
return
except pa.ArrowNotImplementedError:
# ArrowNotImplementedError: Function 'if_else' has no kernel
# matching input types (bool, duration[ns], duration[ns])
# TODO: remove try/except wrapper if/when pyarrow implements
# a kernel for duration types.
pass
elif len(value) == len(self):
if isinstance(value, type(self)) and value.dtype == self.dtype:
self._data = value._data
else:
arr = pa.array(value, type=self._data.type, from_pandas=True)
self._data = pa.chunked_array([arr])
return

indices = self._indexing_key_to_indices(key)

argsort = np.argsort(indices)
indices = indices[argsort]

Expand Down