从ND到一维阵列 [英] 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.ndarray.flatten (用于一维副本)或
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到一维阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!