I have a numpy array as
我有一个numpy数组
[[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
...,
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]]
I would like to have it as
我想拥有它
0
0
0
.
.
0
0
I know that we have to use the reshape function, but how to use it, is I am not able to figure out,
我知道我们必须使用reshape函数,但如何使用它,我无法弄清楚,
my attempt
我的尝试
np.reshape(new_arr, newshape=1)
Which gives an error
这给出了一个错误
ValueError: total size of new array must be unchanged
The documentation isn't very friendly
文档不是很友好
3 个解决方案
#1
6
You can also have a look at numpy.ndarray.flatten:
你也可以看看numpy.ndarray.flatten:
a = np.array([[1,2], [3,4]])
a.flatten()
# array([1, 2, 3, 4])
The difference between flatten
and ravel
is that flatten will return a copy of the array whereas ravel will refence the original if possible. Thus, if you modify the array returned by ravel, it may also modify the entries in the original array.
flatten和ravel之间的区别在于flatten将返回数组的副本,而ravel将在可能的情况下反射原始数据。因此,如果修改ravel返回的数组,它也可能会修改原始数组中的条目。
It is usually safer to create a copy of the original array, although it will take more time since it has to allocate new memory to create it.
创建原始数组的副本通常更安全,但由于必须分配新内存来创建它,因此需要更多时间。
You can read more about the difference between these two options here.
您可以在此处详细了解这两个选项之间的区别。
#2
1
According to the documentation:
根据文件:
np.reshape(new_arr, newshape=n*m)
where n
and m
are the number of rows and columns, respectively, of new_arr
其中n和m分别是new_arr的行数和列数
#3
0
Use the ravel()
method :
使用ravel()方法:
In [1]: arr = np.zeros((2, 2))
In [2]: arr
Out[2]:
array([[ 0., 0.],
[ 0., 0.]])
In [3]: arr.ravel()
Out[3]: array([ 0., 0., 0., 0.])
#1
6
You can also have a look at numpy.ndarray.flatten:
你也可以看看numpy.ndarray.flatten:
a = np.array([[1,2], [3,4]])
a.flatten()
# array([1, 2, 3, 4])
The difference between flatten
and ravel
is that flatten will return a copy of the array whereas ravel will refence the original if possible. Thus, if you modify the array returned by ravel, it may also modify the entries in the original array.
flatten和ravel之间的区别在于flatten将返回数组的副本,而ravel将在可能的情况下反射原始数据。因此,如果修改ravel返回的数组,它也可能会修改原始数组中的条目。
It is usually safer to create a copy of the original array, although it will take more time since it has to allocate new memory to create it.
创建原始数组的副本通常更安全,但由于必须分配新内存来创建它,因此需要更多时间。
You can read more about the difference between these two options here.
您可以在此处详细了解这两个选项之间的区别。
#2
1
According to the documentation:
根据文件:
np.reshape(new_arr, newshape=n*m)
where n
and m
are the number of rows and columns, respectively, of new_arr
其中n和m分别是new_arr的行数和列数
#3
0
Use the ravel()
method :
使用ravel()方法:
In [1]: arr = np.zeros((2, 2))
In [2]: arr
Out[2]:
array([[ 0., 0.],
[ 0., 0.]])
In [3]: arr.ravel()
Out[3]: array([ 0., 0., 0., 0.])