18

I have numeric data stored in two DataFrames x and y. The inner product from numpy works but the dot product from pandas does not.

In [63]: x.shape
Out[63]: (1062, 36)

In [64]: y.shape
Out[64]: (36, 36)

In [65]: np.inner(x, y).shape
Out[65]: (1062L, 36L)

In [66]: x.dot(y)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-66-76c015be254b> in <module>()
----> 1 x.dot(y)

C:\Programs\WinPython-64bit-2.7.3.3\python-2.7.3.amd64\lib\site-packages\pandas\core\frame.pyc in dot(self, other)
    888             if (len(common) > len(self.columns) or
    889                     len(common) > len(other.index)):
--> 890                 raise ValueError('matrices are not aligned')
    891 
    892             left = self.reindex(columns=common, copy=False)

ValueError: matrices are not aligned

Is this a bug or am I using pandas wrong?

4

1 回答 1

40

不仅x和的形状y必须正确,而且 的列名也x必须与 的索引名匹配y。否则,此代码pandas/core/frame.py将引发 ValueError:

if isinstance(other, (Series, DataFrame)):
    common = self.columns.union(other.index)
    if (len(common) > len(self.columns) or
        len(common) > len(other.index)):
        raise ValueError('matrices are not aligned')

如果您只想计算矩阵乘积而不使 的列名x与 的索引名匹配y,则使用 NumPy 点函数:

np.dot(x, y)

的列名x必须匹配的索引名的y原因是因为pandasdot方法会重新索引xy所以如果的列顺序x和索引顺序y不自然匹配,会在执行矩阵乘积之前使它们匹配:

left = self.reindex(columns=common, copy=False)
right = other.reindex(index=common, copy=False)

NumPydot函数不做这样的事情。它只会根据底层数组中的值计算矩阵乘积。


这是一个重现错误的示例:

import pandas as pd
import numpy as np

columns = ['col{}'.format(i) for i in range(36)]
x = pd.DataFrame(np.random.random((1062, 36)), columns=columns)
y = pd.DataFrame(np.random.random((36, 36)))

print(np.dot(x, y).shape)
# (1062, 36)

print(x.dot(y).shape)
# ValueError: matrices are not aligned
于 2013-05-09T23:47:30.670 回答