使用类似形状的函数获得一维numpy.array的"1"

Cov*_*ich 8 python arrays numpy dimension multidimensional-array

在一个函数中,我给出了一个Numpy数组:它可以是多维的,也可以是一维的

所以当我给出一个多维数组:

np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]).shape
>>> (3, 4)
Run Code Online (Sandbox Code Playgroud)

np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]).shape[1]
>>> 4
Run Code Online (Sandbox Code Playgroud)

精细.

但是当我问到它的形状时

np.array([1,2,3,4]).shape
>>> (4,)
Run Code Online (Sandbox Code Playgroud)

np.array([1,2,3,4]).shape[1]
>>> IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)

哎呀,元组只包含一个元素......而我想1表明它是一个一维数组.有没有办法得到这个?我的意思是一个简单的函数或方法,并没有一个判别测试ndim例如?

谢谢 !

wim*_*wim 10

>>> a
array([1, 2, 3, 4])
>>> a.ndim
1
>>> b = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
>>> b.ndim
2
Run Code Online (Sandbox Code Playgroud)

如果你想要一个列向量,你可以使用该.reshape方法 - 实际上,.shape它实际上是一个可设置的属性,所以numpy也允许你这样做:

>>> a
array([1, 2, 3, 4])
>>> a.shape += (1,)
>>> a
array([[1],
       [2],
       [3],
       [4]])
>>> a.shape
(4, 1)
>>> a.ndim
2
Run Code Online (Sandbox Code Playgroud)