diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7f414b8eeee14..e1a910244e673 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -710,20 +710,29 @@ def __neg__(self): def dot(self, other): """ - Matrix multiplication with DataFrame objects. Does no data alignment + Matrix multiplication with DataFrame or Series objects Parameters ---------- - other : DataFrame + other : DataFrame or Series Returns ------- - dot_product : DataFrame - """ - lvals = self.values - rvals = other.values - result = np.dot(lvals, rvals) - return DataFrame(result, index=self.index, columns=other.columns) + dot_product : DataFrame or Series + """ + common = self.columns.union(other.index) + if len(common) > len(self.columns) or len(common) > len(other.index): + raise ValueError('matrices are not aligned') + left = self.reindex(columns=common, copy=False) + right = other.reindex(index=common, copy=False) + lvals = left.values + rvals = right.values + if isinstance(other, DataFrame): + return DataFrame(np.dot(lvals, rvals), index=self.index, columns=other.columns) + elif isinstance(other, Series): + return Series(np.dot(lvals, rvals), index=left.index) + else: + raise TypeError('unsupported type: %s' % type(other)) #---------------------------------------------------------------------- # IO methods (to / from other formats) diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 91dfe3367b940..7335b52e4fc66 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -6629,8 +6629,17 @@ def test_dot(self): expected = DataFrame(np.dot(a.values, b.values), index=['a', 'b', 'c'], columns=['one', 'two']) + #Check alignment + b1 = b.reindex(index=reversed(b.index)) + result = a.dot(b) assert_frame_equal(result, expected) + #Check series argument + result = a.dot(b['one']) + assert_series_equal(result, expected['one']) + result = a.dot(b1['one']) + assert_series_equal(result, expected['one']) + def test_idxmin(self): frame = self.frame frame.ix[5:10] = np.nan