My problem is that I've got this array:
np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
and I want to convert the elements to array like this:
np.array([[0.0], [0.0], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
So is there a loop or a numpy function that I could use to do this task?
答案 0 :(得分:14)
Or simply:
arr[:,None]
# array([[ 0. ],
# [ 0. ],
# [-1.2],
# [-1.2],
# [-3.4],
# [-3.4],
# [-4.5],
# [-4.5]])
答案 1 :(得分:7)
You can use a list comprehension:
>>> a1 = np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
>>> np.array([[x] for x in a1])
array([[ 0. ],
[ 0. ],
[-1.2],
[-1.2],
[-3.4],
[-3.4],
[-4.5],
[-4.5]])
>>>
答案 2 :(得分:6)
Isn't this just a reshape
operation from row to column vector?
In [1]: import numpy as np
In [2]: x = np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
In [3]: np.reshape(x, (-1,1))
Out[3]:
array([[ 0. ],
[ 0. ],
[-1.2],
[-1.2],
[-3.4],
[-3.4],
[-4.5],
[-4.5]])
答案 3 :(得分:1)
使用numpy函数可以通过多种方式实现此目的:
np.expand_dims
- 显式选项
>>> import numpy as np
>>> a = np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5])
>>> np.expand_dims(a, axis=1)
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
使用np.newaxis
切片(None
的别名)
>>> np.array(a)[:, np.newaxis]
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
>>> np.array(a)[:, None]
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
除了手动添加axis
之外,您还可以使用一些默认方式创建多维数组,然后交换轴,例如使用np.transpose
,但您也可以使用np.swapaxes
或np.reshape
:
np.array
,ndmin = 2
>>> np.array([0.0, 0.0, -1.2, -1.2, -3.4, -3.4, -4.5, -4.5], ndmin=2).T
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])
>>> np.atleast_2d(a).swapaxes(1, 0)
array([[ 0. ], [ 0. ], [-1.2], [-1.2], [-3.4], [-3.4], [-4.5], [-4.5]])