Sau*_*tro 5 python arrays numpy
在许多情况下,2D阵列中的切片操作会产生一维数组作为输出,例如:
a = np.random.random((3,3))
# array([[ 0.4986962 , 0.65777899, 0.16798398],
# [ 0.02767355, 0.49157946, 0.03178513],
# [ 0.60765513, 0.65030948, 0.14786596]])
a[0,:]
# array([ 0.4986962 , 0.65777899, 0.16798398])
Run Code Online (Sandbox Code Playgroud)
有一些解决方法,如:
a[0:1,:]
# or
a[0,:][np.newaxis,:]
# array([[ 0.4986962 , 0.65777899, 0.16798398]])
Run Code Online (Sandbox Code Playgroud)
是否有numpy内置函数将输入数组转换为给定数量的维度?喜欢:
np.minndim(a, ndim=2)
Run Code Online (Sandbox Code Playgroud)
有np.array(array, copy=False, subok=True, ndmin=N).np.atleast_1d实际上使用reshape方法,可能更好地支持一些奇怪的子类,如矩阵.
对于2-D中的大多数切片操作,您实际上可以使用矩阵类,但我强烈建议将使用限制在代码中使用其功能的那几个点.