有了Numpy,我想我可以用这种方式创建一个矩阵
z = np.array( [np.linspace(0, 1, 2), np.ones((1, 2)), np.ones((1, 2))] )然而,它给了我:
array([array([ 0., 1.]), array([[ 1., 1.]]), array([[ 1., 1.]])], dtype=object)然后检查它的形状:
>>> z.shape (3,)列维度不存在。 所以我想我有一个包含三个数组对象的数组。
如何在这里使用linespace()和ones()来获得3 x 2矩阵?
With Numpy, I thought I could create a matrix this way
z = np.array( [np.linspace(0, 1, 2), np.ones((1, 2)), np.ones((1, 2))] )which, however, gives me:
array([array([ 0., 1.]), array([[ 1., 1.]]), array([[ 1., 1.]])], dtype=object)then checking its shape:
>>> z.shape (3,)The column dimension does not exist. So I think I got an array with three array objects.
How can I have the 3 x 2 matrix using linespace() and ones() here?
最满意答案
如果输入是1维的,你可以使用numpy.array :
np.array([np.linspace(0, 1, 2), np.ones((2,)), np.ones((2,))])产量
array([[ 0., 1.], [ 1., 1.], [ 1., 1.]])注意, np.ones((1,2))具有二维形状(1,2) ,而np.linspace(0, 1, 2)具有一维形状(2,) 。 要使用np.array创建所需的结果,数组需要具有兼容的形状 - 在这种情况下,这意味着使用1维数组np.ones(2,)而不是np.ones((1,2)) 。
如果你必须使用np.ones((1,2)) ,那么你也可以改为np.linspace(0, 1, 2) 2维,然后使用numpy.vstack :
np.vstack([np.linspace(0, 1, 2)[np.newaxis, :], np.ones((1,2,)), np.ones((1,2,))])产量
array([[ 0., 1.], [ 1., 1.], [ 1., 1.]])If the inputs are 1-dimensional, you could use numpy.array:
np.array([np.linspace(0, 1, 2), np.ones((2,)), np.ones((2,))])yields
array([[ 0., 1.], [ 1., 1.], [ 1., 1.]])Note that np.ones((1,2)) has a 2-dimensional shape (1,2), while np.linspace(0, 1, 2) has a 1-dimensional shape (2,). To create the desired result with np.array, the arrays need to have compatible shapes -- in this case, that means using the 1-dimensional array np.ones(2,) instead of np.ones((1,2)).
If you must use np.ones((1,2)), then you could instead make np.linspace(0, 1, 2) 2-dimensional as well, and then use numpy.vstack:
np.vstack([np.linspace(0, 1, 2)[np.newaxis, :], np.ones((1,2,)), np.ones((1,2,))])yields
array([[ 0., 1.], [ 1., 1.], [ 1., 1.]])更多推荐
发布评论