Skip to content

PERF: DataFrame.corr avoid copy #51421

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 10 commits into from
Mar 14, 2023
Merged
Show file tree
Hide file tree
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
29 changes: 23 additions & 6 deletions pandas/core/internals/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1689,17 +1689,29 @@ def as_array(
-------
arr : ndarray
"""
passed_nan = lib.is_float(na_value) and isna(na_value)

# TODO(CoW) handle case where resulting array is a view
if len(self.blocks) == 0:
arr = np.empty(self.shape, dtype=float)
return arr.transpose()

# We want to copy when na_value is provided to avoid
# mutating the original object
copy = copy or na_value is not lib.no_default

if self.is_single_block:
blk = self.blocks[0]

if na_value is not lib.no_default:
# We want to copy when na_value is provided to avoid
# mutating the original object
if (
isinstance(blk.dtype, np.dtype)
and blk.dtype.kind == "f"
and passed_nan
):
# We are already numpy-float and na_value=np.nan
pass
else:
copy = True

if blk.is_extension:
# Avoid implicit conversion of extension blocks to object

Expand All @@ -1712,7 +1724,8 @@ def as_array(
else:
arr = np.asarray(blk.get_values())
if dtype:
arr = arr.astype(dtype, copy=False)
arr = arr.astype(dtype, copy=copy)
copy = False

if copy:
arr = arr.copy()
Expand All @@ -1724,7 +1737,11 @@ def as_array(
# The underlying data was copied within _interleave, so no need
# to further copy if copy=True or setting na_value

if na_value is not lib.no_default:
if na_value is lib.no_default:
pass
elif arr.dtype.kind == "f" and passed_nan:
pass
else:
arr[isna(arr)] = na_value

return arr.transpose()
Expand Down
4 changes: 4 additions & 0 deletions pandas/tests/frame/methods/test_to_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ def test_to_numpy_copy(self):
assert df.to_numpy(copy=False).base is arr
assert df.to_numpy(copy=True).base is not arr

# we still don't want a copy when na_value=np.nan is passed,
# and that can be respected because we are already numpy-float
assert df.to_numpy(copy=False, na_value=np.nan).base is arr

def test_to_numpy_mixed_dtype_to_str(self):
# https://github.com/pandas-dev/pandas/issues/35455
df = DataFrame([[Timestamp("2020-01-01 00:00:00"), 100.0]])
Expand Down