[英]How do I convert a 2D numpy array into a 1D numpy array of 1D numpy arrays?
换句话说,外部数组的每个元素都是原始2D数组的行向量。
A @Jaime already said, a 2D array can be interpreted as an array of 1D arrays, suppose: @Jaime已经说过,假设2D数组可以解释为1D数组的数组:
a = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
doing a[0]
will return array([1, 2, 3])
. 做
a[0]
将返回array([1, 2, 3])
。
So you don't need to do any conversion. 因此,您无需进行任何转换。
我认为使用numpy数组执行此操作几乎没有意义,只是认为您会错过numpy的所有优点。
I had the same issue to append a raw with a different length to a 2D-array. 我有一个相同的问题,即将具有不同长度的原始数据附加到2D数组。
The only trick I found up to now was to use list comprenhsion and append the new row (see below). 到目前为止,我发现的唯一技巧是使用列表理解并添加新行(请参见下文)。 Not very optimal I guess but at least it works ;-)
我猜不是很理想,但至少它可以工作;-)
Hope this can help 希望这可以帮助
>>> x=np.reshape(np.arange(0,9),(3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> row_to_append = np.arange(9,11)
>>> row_to_append
array([ 9, 10])
>>> result=[item for item in x]
>>> result.append(row_to_append)
>>> result
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8]), array([ 9, 10])]
np.vsplit
Split an array into multiple sub-arrays vertically (row-wise). np.vsplit
一个数组垂直(行)拆分为多个子数组。
x=np.arange(12).reshape(3,4)
In [7]: np.vsplit(x,3)
Out[7]: [array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])]
A comprehension could be used to reshape those arrays into 1d ones. 可以使用一种理解将这些数组整形为一维数组。
This is a list of arrays, not an array of arrays. 这是一个数组列表,而不是数组数组。 Such a sequence of arrays can be recombined with
vstack
(or hstack, dstack). 这样的数组序列可以与
vstack
(或hstack,dstack)重组。
np.array([np.arange(3),np.arange(4)])
makes a 2 element array of arrays. 制作2个元素的数组。 But if the arrays in the list are all the same shape (or compatible), it makes a 2d array.
但是,如果列表中的数组都具有相同的形状(或兼容),那么它将构成一个二维数组。 In terms of data storage it may not matter whether it is 2d or 1d of 1d arrays.
在数据存储方面,无论是2d还是1d的1d阵列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.