抱歉,如果您之前曾问过这个问题,但是我似乎找不到答案,或者我没有正确搜索答案。
我目前正在使用numpy在python中编写代码,并且我的函数将输入作为矩阵。我想将1D数组视为(1 x n)2D数组。
这是我的问题的一个最小的例子。以下函数接受输入两个矩阵,并将第一个矩阵的左上元素相加,然后将其添加到第二个矩阵的右下元素中。
import numpy as np
def add_corners(A, B):
r = A[0, 0] + B[B.shape[0] - 1, B.shape[1] - 1]
return r
C = np.array([[1, 2, 3], [4, 5, 6]])
D = np.array([[9, 8], [7, 6], [5, 4], [10, 11]])
E = np.array([1, 2, 3, 4, 5])
print(add_corners(C, D))
print(add_corners(C, E))
print(add_corners(C,E))
导致错误,因为E.shape[1]
定义不正确。有没有一种方法可以解决此问题而不必添加if语句来检查我的输入是否包含一维数组?也就是说,我要引用E的条目,E[1,x]
而不是just E[x]
。
任何帮助是极大的赞赏!
您需要添加一个附加维度。您可以这样做:
add_corners(C, E[:, None])
或搭配np.expand_dims
:
add_corners(C, np.expand_dims(E, -1))
看起来是这样的:
>>> E
array([1, 2, 3, 4, 5])
>>> E[:, None]
array([[1],
[2],
[3],
[4],
[5]])
>>> E[:, None].shape
(5, 1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句