Home > Mobile >  subtracting every nth array with every nth array
subtracting every nth array with every nth array

Time:10-13

I have an array with the shape (10000,6). For example:

a = np.array([[5, 5, 5, 5, 5, 5][10, 10, 10, 10, 10][15, 15, 15, 15, 15]...])

I want to take every 25th array and subtract its element values from the next 25 elements until a new subtraction array in selected. so for example if the first array is:

[10, 10, 10, 10, 10]

then these values should be subtracted on the array itself and the next 25 arrays until for example a new subtraction array like this is selected:

[2, 2, 2, 2, 2]

then the array itself and the following 25 elements should be subtracted that arrays values. This means that after the operation every 25th array will be:

[0, 0, 0, 0, 0]

because it has been subtracted by itself.

CodePudding user response:

Here's what I would do:

import numpy as np

arr = np.random.randint(0, 10, (9, 3))
group_size = 3
# select vectors you want ot subtract and copy them {group_size} times
selected = arr[::group_size].repeat(3, axis = 0)
# subtract selected vectors from all vectors in the group
sub_arr = arr-selected

output:

arr = 
[[9 6 3]
 [8 3 3]
 [2 0 4]
 [0 3 9]
 [3 9 9]
 [0 8 6]
 [4 0 0]
 [6 1 9]
 [2 6 4]]
selected = 
[[9 6 3]
 [9 6 3]
 [9 6 3]
 [0 3 9]
 [0 3 9]
 [0 3 9]
 [4 0 0]
 [4 0 0]
 [4 0 0]]
sub_arr = 
[[ 0  0  0]
 [-1 -3  0]
 [-7 -6  1]
 [ 0  0  0]
 [ 3  6  0]
 [ 0  5 -3]
 [ 0  0  0]
 [ 2  1  9]
 [-2  6  4]]

CodePudding user response:

You can reshape your array so that each chunk has the right number of lines, and then simply subtract the first line

import numpy as np

a = np.arange(10000)[:, None] * np.ones(6)
a = a.reshape(-1, 25, 6)
a -= a[:, 0, :][:, None, :]
a = a.reshape(-1, 6)
  • Related