Given two numpy arrays, I would like to uniformly increase and decrease each element in the input array and keep track of its impact on the output array. I will present a small example to make my question clearer.
Suppose I have the following array as my input array and would like to increase and decrease each value in each row two times (in real this will be thousands) with the increment of one (i.e., i) add 1s and then subtract 1s, ii) add 2s and subtract 2s etc).
Input = [[6 1 4 4 8 4 6 3 5 8]
[7 9 9 2 7 8 8 9 2 6]
[9 5 4 1 4 6 1 3 4 9]
[2 4 4 4 8 1 2 1 5 8]]
In other words, I would like to obtain:
[[ 7 2 5 5 9 5 7 4 6 9]
[ 5 0 3 3 7 3 5 2 4 7]
[ 8 3 6 6 10 6 8 5 7 10]
[ 4 -1 2 2 6 2 4 1 3 6]
[ 8 10 10 3 8 9 9 10 3 7]
[ 6 8 8 1 6 7 7 8 1 5]
[ 9 11 11 4 9 10 10 11 4 8]
[ 5 7 7 0 5 6 6 7 0 4]
[10 6 5 2 5 7 2 4 5 10]
[ 8 4 3 0 3 5 0 2 3 8]
[11 7 6 3 6 8 3 5 6 11]
[ 7 3 2 -1 2 4 -1 1 2 7]
[ 3 5 5 5 9 2 3 2 6 9]
[ 1 3 3 3 7 0 1 0 4 7]
[ 4 6 6 6 10 3 4 3 7 10]
[ 0 2 2 2 6 -1 0 -1 3 6]]
The second array keeps the output information for each row in the input array.
Output =
[[3]
[2]
[7]
[2]]
I have a parameter called impactFactor which tells me how many of the elements will impact the second array. Suppose impactFactor = 3, then the output will increase by three if the increment is all ones. The output will increase by six if the increment is two. The same logic applies to the subtract case. The expected results for the example provided is:
array([[ 6],
[ 0],
[ 9],
[-3],
[ 5],
[-1],
[ 8],
[-4],
[10],
[ 4],
[13],
[ 1],
[ 5],
[-1],
[ 8],
[-4]])
As a result, I would like to store an updated input and output array. The code that I wrote is as follows and my question is whether it is possible to improve the performance of my code. I appreciate any help.
import numpy as np
import random
#you can change the number of rows and columns
x = np.random.randint(1,100,(4,10))
y = np.random.randint(50,10,(4,1))
rep = 5 #how many different instances will be created
row, col = x.shape
impactFactor = 3
new_x = np.repeat(x, 2*rep, axis=0) #copy the original values fot both increase and decrease cases
arr = np.array([np.full((1, col), j*(i+1)) for i in range(rep) for j in[1,-1]]) # determine increase and decrease values
change = np.repeat(arr[None,:] ,row ,axis=0).reshape(-1, col) # changes will repeat for each point in X
increase_in_y = np.repeat(np.array([[impactFactor*(i+1)*j] for i in range(rep) for j in [1,-1]])[None,:], row , axis=0).reshape(-1, 1) #compute how much each y will increase
repeat_y = np.repeat(y,2*rep,axis=0).reshape(-1, 1) #copy the original y values
new_y= np.add(increase_in_y,repeat_y) #updated y values are here
new_x = np.add(new_x,change) # updated x values are here