Skip to content

Commit 01f4b7b

Browse files
authored
BUG: Fix setitem with 1d matrix (#44669)
1 parent 73b4167 commit 01f4b7b

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

doc/source/whatsnew/v1.3.5.rst

+2
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ Fixed regressions
2222
- Fixed regression in :meth:`Series.duplicated` and :meth:`Series.drop_duplicates` when Series has :class:`Categorical` dtype with boolean categories (:issue:`44351`)
2323
- Fixed regression in :meth:`.GroupBy.sum` with ``timedelta64[ns]`` dtype containing ``NaT`` failing to treat that value as NA (:issue:`42659`)
2424
- Fixed regression in :meth:`.RollingGroupby.cov` and :meth:`.RollingGroupby.corr` when ``other`` had the same shape as each group would incorrectly return superfluous groups in the result (:issue:`42915`)
25+
- Fixed regression where a single column ``np.matrix`` was no longer coerced to a 1d ``np.ndarray`` when added to a :class:`DataFrame` (:issue:`42376`)
26+
2527

2628
.. ---------------------------------------------------------------------------
2729

pandas/core/construction.py

+2
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,8 @@ def sanitize_array(
528528

529529
# GH#846
530530
if isinstance(data, np.ndarray):
531+
if isinstance(data, np.matrix):
532+
data = data.A
531533

532534
if dtype is not None and is_float_dtype(data.dtype) and is_integer_dtype(dtype):
533535
# possibility of nan -> garbage

pandas/tests/frame/indexing/test_setitem.py

+19
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,25 @@ def test_boolean_mask_nullable_int64(self):
680680
)
681681
tm.assert_frame_equal(result, expected)
682682

683+
# TODO(ArrayManager) set column with 2d column array, see #44788
684+
@td.skip_array_manager_not_yet_implemented
685+
def test_setitem_npmatrix_2d(self):
686+
# GH#42376
687+
# for use-case df["x"] = sparse.random(10, 10).mean(axis=1)
688+
expected = DataFrame(
689+
{"np-array": np.ones(10), "np-matrix": np.ones(10)}, index=np.arange(10)
690+
)
691+
692+
a = np.ones((10, 1))
693+
df = DataFrame(index=np.arange(10))
694+
df["np-array"] = a
695+
696+
# Instantiation of `np.matrix` gives PendingDeprecationWarning
697+
with tm.assert_produces_warning(PendingDeprecationWarning):
698+
df["np-matrix"] = np.matrix(a)
699+
700+
tm.assert_frame_equal(df, expected)
701+
683702

684703
class TestSetitemTZAwareValues:
685704
@pytest.fixture

0 commit comments

Comments
 (0)