Skip to content

ERR: error handling in DataFrame.__rmatmul__ #36792

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 1 commit into from
Oct 2, 2020
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ Numeric
- Bug in :meth:`Series.equals` where a ``ValueError`` was raised when numpy arrays were compared to scalars (:issue:`35267`)
- 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`)
- Bug in :meth:`pd._testing.assert_almost_equal` was incorrect for complex numeric types (:issue:`28235`)
-
- Bug in :meth:`DataFrame.__rmatmul__` error handling reporting transposed shapes (:issue:`21581`)

Conversion
^^^^^^^^^^
Expand Down
9 changes: 8 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1216,7 +1216,14 @@ def __rmatmul__(self, other):
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
return self.T.dot(np.transpose(other)).T
try:
return self.T.dot(np.transpose(other)).T
except ValueError as err:
if "shape mismatch" not in str(err):
raise
# GH#21581 give exception message for original shapes
msg = f"shapes {np.shape(other)} and {self.shape} not aligned"
raise ValueError(msg) from err

# ----------------------------------------------------------------------
# IO methods (to / from other formats)
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/frame/test_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -1177,6 +1177,20 @@ def test_matmul(self):
with pytest.raises(ValueError, match="aligned"):
operator.matmul(df, df2)

def test_matmul_message_shapes(self):
# GH#21581 exception message should reflect original shapes,
# not transposed shapes
a = np.random.rand(10, 4)
b = np.random.rand(5, 3)

df = DataFrame(b)

msg = r"shapes \(10, 4\) and \(5, 3\) not aligned"
with pytest.raises(ValueError, match=msg):
a @ df
with pytest.raises(ValueError, match=msg):
a.tolist() @ df

# ---------------------------------------------------------------------
# Unsorted

Expand Down