gpt4 book ai didi

python - Pandas 中的矩阵乘法

转载 作者:IT老高 更新时间:2023-10-28 21:18:07 41 4
gpt4 key购买 nike

我将数值数据存储在两个 DataFrame x 和 y 中。 numpy 的内积有效,但 pandas 的点积无效。

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

这是一个错误还是我使用 pandas 错误?

最佳答案

xy 的形状不仅要正确,而且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 的索引名匹配是因为 pandas dot 方法会重新索引 xy 这样如果 x 的列顺序和 y 的索引顺序不自然匹配,它们将是在执行矩阵乘积之前进行匹配:

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

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


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

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

关于python - Pandas 中的矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16472729/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com