Python:如何用一系列数字填充数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37473697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: How do I fill an array with a range of numbers?
提问by hpnk85
So I have an array of 100 elements:
所以我有一个包含 100 个元素的数组:
a = np.empty(100)
How do I fill it with a range of numbers? I want something like this:
我如何用一系列数字填充它?我想要这样的东西:
b = a.fill(np.arange(1, 4, 0.25))
So I want it to keep filling a
with that values of that range on and on until it reaches the size of it
所以我希望它不断填充a
该范围的值,直到达到它的大小
Thanks
谢谢
回答by unutbu
np.put
places values from b
into a
at the target indices, ind
. If v
is shorter than ind
, its values are repeated as necessary:
np.put
将来自b
into 的值放置a
在目标索引处ind
。如果v
短于ind
,则根据需要重复其值:
import numpy as np
a = np.empty(100)
b = np.arange(1, 4, 0.25)
ind = np.arange(len(a))
np.put(a, ind, b)
print(a)
yields
产量
[ 1. 1.25 1.5 1.75 2. 2.25 2.5 2.75 3. 3.25 3.5 3.75
1. 1.25 1.5 1.75 2. 2.25 2.5 2.75 3. 3.25 3.5 3.75
1. 1.25 1.5 1.75 2. 2.25 2.5 2.75 3. 3.25 3.5 3.75
1. 1.25 1.5 1.75 2. 2.25 2.5 2.75 3. 3.25 3.5 3.75
1. 1.25 1.5 1.75 2. 2.25 2.5 2.75 3. 3.25 3.5 3.75
1. 1.25 1.5 1.75 2. 2.25 2.5 2.75 3. 3.25 3.5 3.75
1. 1.25 1.5 1.75 2. 2.25 2.5 2.75 3. 3.25 3.5 3.75
1. 1.25 1.5 1.75 2. 2.25 2.5 2.75 3. 3.25 3.5 3.75
1. 1.25 1.5 1.75]
回答by Ravi Sankar Raju
updating solution to fit description
更新解决方案以适应描述
a = np.empty(100)
filler = np.arange(1,4,0.25)
index = np.arange(a.size)
np.put(a,index,filler)