Numpy 将所有索引设置为一个值

Numpy set all indexes to a value

我有一个 numpy ndarray a = np.ndarray((3,3)) 并且我希望所有索引都以相同的值开始,例如5:

array([[5., 5., 5.],
       [5., 5., 5.],
       [5., 5., 5.]])

注意:我发布这种问答风格是因为每次我查找它时,我总是会发现一堆关于复杂切片的随机问题,而不是一次转换所有内容的简单示例。希望下次我搜索这个问题时,这会作为更直接的结果弹出。 但也希望别人有好的点子我可以采纳

这里有一些可靠的方法:

# Use the function built for this very purpose
>>> a = np.full((3, 3), 5)
>>> a
array([[5., 5., 5.],
       [5., 5., 5.],
       [5., 5., 5.]])

# [:] is shorthand for every index.
>>> a = np.ndarray((3,3))
>>> a[:] = 5
>>> a
array([[5., 5., 5.],
       [5., 5., 5.],
       [5., 5., 5.]])

# multiply a single value over every index (currently all 1s)
>>> a = np.ones((3,3)) * 5   
>>> a
array([[5., 5., 5.],
       [5., 5., 5.],
       [5., 5., 5.]])

查看有关索引的 documentation 了解更多详细信息和复杂 indexing/slicing

的示例

我似乎有另一种方法,只需使用加号运算符即可:

>>> import numpy as np
>>> a = np.zeros((3,3))
>>> a
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> a + 5
array([[ 5.,  5.,  5.],
       [ 5.,  5.,  5.],
       [ 5.,  5.,  5.]])
>>> 

(P.S 使用 zeros 而不是 ndarray)

有几种方法可以实现这一点,但我认为重点是分析哪种方法会给您带来最佳结果:

In[1]: %timeit np.ones((3,3)) * 5
6.82 µs ± 374 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)    
In[2]: %%timeit
       np.ndarray((3,3))
       a[:] = 5
1.96 µs ± 29.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In[3]: %timeit np.full((3, 3), 5)
4.13 µs ± 59.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

因此,最好的方法可能是创建数组并将值 5 分配给所有元素,这意味着使用第二个选项。