Skip to content

Commit 0ebf3f4

Browse files
committed
BUG: 2D ndarray of dtype 'object' is always copied upon construction (pandas-dev#39263)
1 parent 9e5573e commit 0ebf3f4

File tree

4 files changed

+55
-31
lines changed

4 files changed

+55
-31
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,7 @@ Datetimelike
234234
- Bug in :meth:`Series.where` incorrectly casting ``datetime64`` values to ``int64`` (:issue:`37682`)
235235
- Bug in :class:`Categorical` incorrectly typecasting ``datetime`` object to ``Timestamp`` (:issue:`38878`)
236236
- Bug in :func:`date_range` incorrectly creating :class:`DatetimeIndex` containing ``NaT`` instead of raising ``OutOfBoundsDatetime`` in corner cases (:issue:`24124`)
237+
- Bug in :func:`DataFrame` constructor unnecessarily copying 2D object arrays (:issue:`39263`)
237238

238239
Timedelta
239240
^^^^^^^^^

pandas/core/internals/construction.py

+2-31
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
dict_compat,
2828
maybe_cast_to_datetime,
2929
maybe_convert_platform,
30-
maybe_infer_to_datetimelike,
3130
maybe_upcast,
3231
)
3332
from pandas.core.dtypes.common import (
@@ -37,7 +36,6 @@
3736
is_integer_dtype,
3837
is_list_like,
3938
is_named_tuple,
40-
is_object_dtype,
4139
)
4240
from pandas.core.dtypes.generic import (
4341
ABCDataFrame,
@@ -58,8 +56,8 @@
5856
union_indexes,
5957
)
6058
from pandas.core.internals.managers import (
59+
create_block_manager_from_array,
6160
create_block_manager_from_arrays,
62-
create_block_manager_from_blocks,
6361
)
6462

6563
if TYPE_CHECKING:
@@ -232,34 +230,7 @@ def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool):
232230
)
233231
values = values.T
234232

235-
# if we don't have a dtype specified, then try to convert objects
236-
# on the entire block; this is to convert if we have datetimelike's
237-
# embedded in an object type
238-
if dtype is None and is_object_dtype(values.dtype):
239-
240-
if values.ndim == 2 and values.shape[0] != 1:
241-
# transpose and separate blocks
242-
243-
dvals_list = [maybe_infer_to_datetimelike(row) for row in values]
244-
for n in range(len(dvals_list)):
245-
if isinstance(dvals_list[n], np.ndarray):
246-
dvals_list[n] = dvals_list[n].reshape(1, -1)
247-
248-
from pandas.core.internals.blocks import make_block
249-
250-
# TODO: What about re-joining object columns?
251-
block_values = [
252-
make_block(dvals_list[n], placement=[n], ndim=2)
253-
for n in range(len(dvals_list))
254-
]
255-
256-
else:
257-
datelike_vals = maybe_infer_to_datetimelike(values)
258-
block_values = [datelike_vals]
259-
else:
260-
block_values = [values]
261-
262-
return create_block_manager_from_blocks(block_values, [columns, index])
233+
return create_block_manager_from_array(values, [columns, index], dtype)
263234

264235

265236
def init_dict(data: Dict, index, columns, dtype: Optional[DtypeObj] = None):

pandas/core/internals/managers.py

+44
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,15 @@
2727
from pandas.core.dtypes.cast import (
2828
find_common_type,
2929
infer_dtype_from_scalar,
30+
maybe_infer_to_datetimelike,
3031
maybe_promote,
3132
)
3233
from pandas.core.dtypes.common import (
3334
DT64NS_DTYPE,
3435
is_dtype_equal,
3536
is_extension_array_dtype,
3637
is_list_like,
38+
is_object_dtype,
3739
)
3840
from pandas.core.dtypes.concat import concat_compat
3941
from pandas.core.dtypes.dtypes import ExtensionDtype
@@ -1678,6 +1680,41 @@ def create_block_manager_from_arrays(
16781680
raise construction_error(len(arrays), arrays[0].shape, axes, e)
16791681

16801682

1683+
def create_block_manager_from_array(
1684+
array, axes: List[Index], dtype: Optional[Dtype] = None
1685+
) -> BlockManager:
1686+
assert isinstance(axes, list)
1687+
assert all(isinstance(x, Index) for x in axes)
1688+
1689+
# ensure we dont have any PandasArrays when we call get_block_type
1690+
# Note: just calling extract_array breaks tests that patch PandasArray._typ.
1691+
array = array if not isinstance(array, ABCPandasArray) else array.to_numpy()
1692+
1693+
try:
1694+
# if we don't have a dtype specified, then try to convert objects
1695+
# on the entire block; this is to convert if we have datetimelike's
1696+
# embedded in an object type
1697+
if dtype is None and is_object_dtype(array.dtype):
1698+
maybe_datetime = [
1699+
maybe_infer_to_datetimelike(instance) for instance in array
1700+
]
1701+
# don't convert (and copy) the objects if no type conversion occurs
1702+
if any(
1703+
not is_dtype_equal(instance.dtype, array.dtype)
1704+
for instance in maybe_datetime
1705+
):
1706+
blocks = _form_blocks(maybe_datetime, axes[0], axes)
1707+
else:
1708+
blocks = [make_block(array, slice(0, len(axes[0])))]
1709+
else:
1710+
blocks = [make_block(array, slice(0, len(axes[0])), dtype=dtype)]
1711+
mgr = BlockManager(blocks, axes)
1712+
mgr._consolidate_inplace()
1713+
return mgr
1714+
except ValueError as e:
1715+
raise construction_error(array.shape[0], array.shape[1:], axes, e)
1716+
1717+
16811718
def construction_error(tot_items, block_shape, axes, e=None):
16821719
""" raise a helpful message about our construction """
16831720
passed = tuple(map(int, [tot_items] + list(block_shape)))
@@ -1705,6 +1742,13 @@ def construction_error(tot_items, block_shape, axes, e=None):
17051742
def _form_blocks(arrays, names: Index, axes) -> List[Block]:
17061743
# put "leftover" items in float bucket, where else?
17071744
# generalize?
1745+
1746+
if len(arrays) != len(names):
1747+
raise ValueError(
1748+
f"Number of arrays ({len(arrays)}) "
1749+
f"does not match index length ({len(names)})"
1750+
)
1751+
17081752
items_dict: DefaultDict[str, List] = defaultdict(list)
17091753
extra_locs = []
17101754

pandas/tests/frame/test_constructors.py

+8
Original file line numberDiff line numberDiff line change
@@ -2267,6 +2267,14 @@ def test_nested_dict_construction(self):
22672267
)
22682268
tm.assert_frame_equal(result, expected)
22692269

2270+
def test_object_array_does_not_copy(self):
2271+
a = np.array(["a", "b"], dtype="object")
2272+
b = np.array([["a", "b"], ["c", "d"]], dtype="object")
2273+
df = DataFrame(a)
2274+
assert np.shares_memory(df.values, a)
2275+
df2 = DataFrame(b)
2276+
assert np.shares_memory(df2.values, b)
2277+
22702278
def test_from_tzaware_object_array(self):
22712279
# GH#26825 2D object array of tzaware timestamps should not raise
22722280
dti = date_range("2016-04-05 04:30", periods=3, tz="UTC")

0 commit comments

Comments
 (0)