简体   繁体   中英

how to insert a squence with slight modification in a numpy array?

I have a fixed list and a fixed size numpy array.

data = [10,20,30]
arr = np.zeros(9)

I want to insert the data in NumPy arr with some slight modification so that the expected output should look like this:

arr = [10, 20, 30, 9, 22, 32, 13, 16, 28]

the difference between the values can be in the range of (-5, 5) my attept was:

import numpy as np
data = [10,20,30]
dataArr = np.zeros(9)
for i in range(9):
    for j in data:
        dataArr[3*i:3*(i+1)] = random.randint(int(j - 5), int(j + 5))
dataArr

but it gives me this output:

array([34., 34., 34., 33., 33., 33., 35., 35., 35.])

can somebody please help?

When you do

dataArr[3*i:3*(i+1)] = value

You are setting the entire range to value . In fact your indices even go beyond the range of dataArr , even though it doesn't raise an exception. See after execution :

print(dataArr[3*i:3*(i+1)])
# output:
# []

Iterate over the values of data , and modify the three corresponding values in dataArr by doing so:

nbOfRepetitions = 3
dataArr = np.zeros(len(data)*nbOfRepetitions)
for i in range(len(data)):
    dataArr[i] = data[i]
    for j in range(1, nbOfRepetitions):
        dataArr[i+len(data)*j] = random.randint(int(data[i] - 5), int(data[i] + 5))

Where nbOfRepetitions is the number of time you want to have data in dataArr (this includes the non-modified copy at the start). This gives the expected result.

array([10., 20., 30., 12., 18., 30., 10., 24., 28.])

Edited to generalize for different sizes for data and dataArr .

If you want to skip the first N items that are already in your data array, you can change your inner loop and access indices to something like:

import random
import numpy as np
MAX_LENGTH = 9
data = [10,20,30]
dataArr = np.zeros(MAX_LENGTH)
for i in range(MAX_LENGTH):
    for j in range(len(data),MAX_LENGTH):
        dataArr[j] = random.randint((min(data) - 5), (max(data) + 5))
dataArr[0:len(data)] = data

# output:
array([10., 20., 30., 28., 31., 17., 30., 30., 10.])

Other than above solution , this can be also one more way

import numpy as np
(
    (np.random.randint(10, size=(3, 3)) - 5) +
    np.array([10, 20, 30])
).reshape(-1)

First get 3x3 matrix of random integers from 0-10 and subtract 5 to get from -5 to 5

Before adding np.array([10, 20, 30]) will be broadcasted along 0 axis like np.array([10, 20, 30])[np.newaxis, :] and towards end flattening

您需要设置数组以使用整数类型:

dataArr = np.zeros(9, dtype=int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM