Skip to content

Commit a5addfb

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

File tree

3 files changed

+31
-9
lines changed

3 files changed

+31
-9
lines changed

doc/source/whatsnew/v1.2.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ Bug fixes
4949
- Bug in :meth:`read_csv` with ``float_precision="high"`` caused segfault or wrong parsing of long exponent strings. This resulted in a regression in some cases as the default for ``float_precision`` was changed in pandas 1.2.0 (:issue:`38753`)
5050
- Bug in :func:`read_csv` not closing an opened file handle when a ``csv.Error`` or ``UnicodeDecodeError`` occurred while initializing (:issue:`39024`)
5151
- Bug in :func:`pandas.testing.assert_index_equal` raising ``TypeError`` with ``check_order=False`` when :class:`Index` has mixed dtype (:issue:`39168`)
52+
- Bug in :func:`pandas.core.internals.construction.init_ndarray` unnecessarily copying all object arrays after datetime inference
5253

5354
.. ---------------------------------------------------------------------------
5455

pandas/core/internals/construction.py

+22-9
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
constructors before passing them to a BlockManager.
44
"""
55
from collections import abc
6+
from itertools import groupby
7+
from operator import itemgetter
68
from typing import (
79
TYPE_CHECKING,
810
Any,
@@ -240,18 +242,29 @@ def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool):
240242
if values.ndim == 2 and values.shape[0] != 1:
241243
# transpose and separate blocks
242244

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)
245+
dvals_list = (maybe_infer_to_datetimelike(row) for row in values)
247246

248247
from pandas.core.internals.blocks import make_block
249248

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-
]
249+
i = 0
250+
block_values = []
251+
for is_object, group in groupby(
252+
dvals_list, lambda row: is_object_dtype(row.dtype)
253+
):
254+
dval_group = list(group)
255+
ei = i + len(dval_group)
256+
if is_object:
257+
block_values.append(values[i:ei])
258+
else:
259+
block_values.extend(
260+
make_block(
261+
row.reshape(1, -1) if isinstance(row, np.ndarray) else row,
262+
placement=[i + incr],
263+
ndim=2,
264+
)
265+
for incr, row in enumerate(dval_group)
266+
)
267+
i = ei
255268

256269
else:
257270
datelike_vals = maybe_infer_to_datetimelike(values)

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 = pd.DataFrame(a)
2274+
assert np.shares_memory(df.values, a)
2275+
df2 = pd.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)