从 ND 到 1D 阵列 [英] From ND to 1D arrays
问题描述
假设我有一个数组 a
:
a = np.array([[1,2,3], [4,5,6]])
array([[1, 2, 3],
[4, 5, 6]])
我想将其转换为一维数组(即列向量):
I would like to convert it to a 1D array (i.e. a column vector):
b = np.reshape(a, (1,np.product(a.shape)))
但这会返回
array([[1, 2, 3, 4, 5, 6]])
与以下不同:
array([1, 2, 3, 4, 5, 6])
我可以把这个数组的第一个元素手动转换成一维数组:
I can take the first element of this array to manually convert it to a 1D array:
b = np.reshape(a, (1,np.product(a.shape)))[0]
但这需要我知道原始数组有多少维(并在处理更高维时连接 [0])
but this requires me to know how many dimensions the original array has (and concatenate [0]'s when working with higher dimensions)
是否有一种从任意 ndarray 中获取列/行向量的与维度无关的方法?
Is there a dimensions-independent way of getting a column/row vector from an arbitrary ndarray?
推荐答案
使用 np.ravel(用于一维视图)或 np.ndarray.flatten(用于一维副本)或 np.ndarray.flat(用于一维迭代器):
Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):
In [12]: a = np.array([[1,2,3], [4,5,6]])
In [13]: b = a.ravel()
In [14]: b
Out[14]: array([1, 2, 3, 4, 5, 6])
请注意,ravel()
在可能的情况下返回 a
的 view
.所以修改b
也会修改a
.当一维元素在内存中是连续的时,ravel()
返回一个 view
,但如果例如 a
是通过使用非单位步长(例如 a = x[::2]
)对另一个数组进行切片而制成的.
Note that ravel()
returns a view
of a
when possible. So modifying b
also modifies a
. ravel()
returns a view
when the 1D elements are contiguous in memory, but would return a copy
if, for example, a
were made from slicing another array using a non-unit step size (e.g. a = x[::2]
).
如果您想要副本而不是视图,请使用
If you want a copy rather than a view, use
In [15]: c = a.flatten()
如果你只想要一个迭代器,使用 np.ndarray.flat
:
If you just want an iterator, use np.ndarray.flat
:
In [20]: d = a.flat
In [21]: d
Out[21]: <numpy.flatiter object at 0x8ec2068>
In [22]: list(d)
Out[22]: [1, 2, 3, 4, 5, 6]
这篇关于从 ND 到 1D 阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!