[英]Matrix Manipulation: Subtract 2D Matrix and 3D Matrix in numpy
If I have 3-d Matrix like: 如果我有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
and 2-d matrix like: 和二维矩阵,例如:
d =: 3 3 $ i.5
d
0 1 2
3 4 0
1 2 3
It is really simple to calculate in J language: putting "2 (by 2D matrix) after - sign. 用J语言计算起来真的很简单:在符号后加上“ 2(通过2D矩阵)”。
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
But I am still a numpy novice.... 但是我仍然是一个麻木的新手。
cor - d
ValueError: Unable to coerce to Series/DataFrame, dim must be <= 2: (59, 59, 59)
Is there anyway that I can manipulate this kind of matrix manipulation in Python Numpy?? 无论如何,我可以在Python Numpy中操纵这种矩阵操纵吗?
Thanks in advance. 提前致谢。
this is the python for loop code that I wanted to change into numpy 这是我想更改为numpy的python for循环代码
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!
You need to match the shape of d (currently (3, 3)) to the shape of cor (currently (3, 3, 3)) before subtraction. 在减去之前,需要将d的形状(当前为(3,3))与cor的形状(当前为(3,3,3))匹配。 Try
cor - d[:None]
. 试试
cor - d[:None]
。 This basically tells numpy to use the existing shape of d ( :
) and to create a new axis for the last dimension ( None
). 这主要是告诉numpy的使用d的现有形状(
:
),并用于最后一维(创建新的轴None
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.