Skip to content

REF: collect casting portion of Block.setitem #32940

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 1 commit into from
Mar 25, 2020
Merged
Changes from all 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
30 changes: 12 additions & 18 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -833,21 +833,24 @@ def setitem(self, indexer, value):

else:
# current dtype cannot store value, coerce to common dtype
find_dtype = False

if hasattr(value, "dtype"):
dtype = value.dtype
find_dtype = True

elif lib.is_scalar(value) and not isna(value):
dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)
find_dtype = True

if find_dtype:
dtype = find_common_type([values.dtype, dtype])
if not is_dtype_equal(self.dtype, dtype):
b = self.astype(dtype)
return b.setitem(indexer, value)
else:
# e.g. we are bool dtype and value is nan
# TODO: watch out for case with listlike value and scalar/empty indexer
dtype, _ = maybe_promote(np.array(value).dtype)
return self.astype(dtype).setitem(indexer, value)

dtype = find_common_type([values.dtype, dtype])
assert not is_dtype_equal(self.dtype, dtype)
# otherwise should have _can_hold_element

return self.astype(dtype).setitem(indexer, value)
Copy link
Contributor

Choose a reason for hiding this comment

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

do we do copy=False internally in .astype?

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's the default kwarg for Block.astype, yes


# value must be storeable at this moment
if is_extension_array_dtype(getattr(value, "dtype", None)):
Expand All @@ -857,11 +860,6 @@ def setitem(self, indexer, value):
else:
arr_value = np.array(value)

# cast the values to a type that can hold nan (if necessary)
if not self._can_hold_element(value):
dtype, _ = maybe_promote(arr_value.dtype)
values = values.astype(dtype)

if transpose:
values = values.T

Expand All @@ -881,11 +879,7 @@ def setitem(self, indexer, value):
# be e.g. a list; see GH#6043
values[indexer] = value

elif (
exact_match
and is_categorical_dtype(arr_value.dtype)
and not is_categorical_dtype(values)
):
elif exact_match and is_categorical_dtype(arr_value.dtype):
# GH25495 - If the current dtype is not categorical,
# we need to create a new categorical block
values[indexer] = value
Expand Down