矩阵操作:在 numpy 中减去 2D 矩阵和 3D 矩阵

Matrix Manipulation: Subtract 2D Matrix and 3D Matrix in numpy

如果我有像这样的 3-d 矩阵:

cor =: 3 3 3 $ i.5
   cor
0 1 2
3 4 0
1 2 3

4 0 1
2 3 4
0 1 2

3 4 0
1 2 3
4 0 1

和二维矩阵如:

d  =: 3 3 $ i.5

   d
0 1 2
3 4 0
1 2 3

J语言计算真的很简单:把"2(by 2D matrix)放在-号后面。

d -"2 cor
 0  0  0
 0  0  0
 0  0  0

_4  1  1
 1  1 _4
 1  1  1

_3 _3  2
 2  2 _3
_3  2  2

但我还是一个麻木的新手....

cor - d 

ValueError: Unable to coerce to Series/DataFrame, dim must be <= 2: (59, 59, 59)

无论如何我可以在 Python Numpy 中操作这种矩阵操作吗??

提前致谢。


这是 python for 循环代码,我想将其更改为 numpy

def pcor(df):
    cor = df.corr()
    n = df.shape[1] # number of indices 
    pcor = np.empty((n, n, n))
    d = np.empty((n, n, n))
    for x in range(n):
        for y in range(n):
            for m in range(n):
                if x==y:
                    pcor[x,y,m] = float('nan')
                else:
                    pcor[x,y,m] = (cor.iloc[x,y] - cor.iloc[x,m]*cor.iloc[y,m])/((1-cor.iloc[x,m]**2)*(1-cor.iloc[y,m]**2))**(1/2)
                    d[x,y,m] = cor.iloc[x,y] - pcor[x,y,m] # <-- this part!

在减法之前,您需要将 d(当前为 (3, 3))的形状与 cor(当前为 (3, 3, 3))的形状相匹配。尝试 cor - d[:None]。这基本上告诉 numpy 使用 d 的现有形状 (:) 并为最后一个维度 (None) 创建一个新轴。