Skip to content

Commit 3787913

Browse files
authored
ERR: error handling in DataFrame.__rmatmul__ (#36792)
1 parent d9feaed commit 3787913

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

doc/source/whatsnew/v1.2.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ Numeric
327327
- Bug in :meth:`Series.equals` where a ``ValueError`` was raised when numpy arrays were compared to scalars (:issue:`35267`)
328328
- Bug in :class:`Series` where two :class:`Series` each have a :class:`DatetimeIndex` with different timezones having those indexes incorrectly changed when performing arithmetic operations (:issue:`33671`)
329329
- Bug in :meth:`pd._testing.assert_almost_equal` was incorrect for complex numeric types (:issue:`28235`)
330-
-
330+
- Bug in :meth:`DataFrame.__rmatmul__` error handling reporting transposed shapes (:issue:`21581`)
331331

332332
Conversion
333333
^^^^^^^^^^

pandas/core/frame.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -1216,7 +1216,14 @@ def __rmatmul__(self, other):
12161216
"""
12171217
Matrix multiplication using binary `@` operator in Python>=3.5.
12181218
"""
1219-
return self.T.dot(np.transpose(other)).T
1219+
try:
1220+
return self.T.dot(np.transpose(other)).T
1221+
except ValueError as err:
1222+
if "shape mismatch" not in str(err):
1223+
raise
1224+
# GH#21581 give exception message for original shapes
1225+
msg = f"shapes {np.shape(other)} and {self.shape} not aligned"
1226+
raise ValueError(msg) from err
12201227

12211228
# ----------------------------------------------------------------------
12221229
# IO methods (to / from other formats)

pandas/tests/frame/test_analytics.py

+14
Original file line numberDiff line numberDiff line change
@@ -1177,6 +1177,20 @@ def test_matmul(self):
11771177
with pytest.raises(ValueError, match="aligned"):
11781178
operator.matmul(df, df2)
11791179

1180+
def test_matmul_message_shapes(self):
1181+
# GH#21581 exception message should reflect original shapes,
1182+
# not transposed shapes
1183+
a = np.random.rand(10, 4)
1184+
b = np.random.rand(5, 3)
1185+
1186+
df = DataFrame(b)
1187+
1188+
msg = r"shapes \(10, 4\) and \(5, 3\) not aligned"
1189+
with pytest.raises(ValueError, match=msg):
1190+
a @ df
1191+
with pytest.raises(ValueError, match=msg):
1192+
a.tolist() @ df
1193+
11801194
# ---------------------------------------------------------------------
11811195
# Unsorted
11821196

0 commit comments

Comments
 (0)