[英]How to assign range(10) to a ndarray which shape is (10, 1) conveniently in Numpy?
I tried this: 我尝试了这个:
import numpy as np
a = np.empty((1, 10, 1), np.int8)
a[0] = range(10)
It throw error: ValueError: could not broadcast input array from shape (10) into shape (10,1)
它引发错误:
ValueError: could not broadcast input array from shape (10) into shape (10,1)
您可以执行a[0, :, 0] = range(10)
。
Several options that work in this case: 在这种情况下可以使用的几个选项:
a[0, :, 0] = np.arange(10) # assign to 1D slice
a[0].flat = range(10) # assign to flattened 2D slice
a[0] = np.arange(10).reshape(10, 1) # bring the rigth side into correct shape
a[0] = np.arange(10)[:, np.newaxis] # bring the rigth side into correct shape
Note the use of np.arange
instead of range
. 注意使用
np.arange
代替range
。 The former directly creates an ndarray with a sequence of values, while the latter creates an iterable that needs to be converted into an array for the assignment. 前者直接创建具有值序列的ndarray,而后者创建需要迭代的可迭代对象,以进行赋值。
In the case of assigning to flat
it makes sense to use range
because both are iterators. 在分配
flat
时,使用range
是有意义的,因为两者都是迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.