Home > Software engineering >  Operation on a specified array's column using same column index - previous row in the array
Operation on a specified array's column using same column index - previous row in the array

Time:11-28

The intention is do it without a for-loop or while-loop and, if it is possible, with a faster loop:

def multiply(x):
    return x * 10


a = np.random.randint(1, 10, size=(5, 5))

print(f"array a = {a}")

a_multiplied = list(map(multiply, a))

print(f"multiply of a = {a_multiplied}")

It begins like this:

array a = [
 [4 6 1 5 9]
 [7 9 4 5 9]
 [8 9 6 5 6]
 [8 6 4 4 3]
 [2 4 2 9 4]
]

And returns this:

multiplied of a = [array([40, 60, 10, 50, 90]), array([70, 90, 40, 50, 90]), array([80, 90, 60, 50, 60]), array([80, 60, 40, 40, 30]), array([20, 40, 20, 90, 40])]

How can I use the previous row and same column to substitute the 10 in my multiply function?

Example:

from this:

array a = [
 [4 6 1 5 9]
 [7 9 4 5 9]
 [8 9 6 5 6]
 [8 6 4 4 3]
 [2 4 2 9 4] 
]

the process:

array a = [
 [4 6 |1| 5 9]
 [7 9 |4| 5 9] Multiply 4 * 1(previus row and same index)
 [8 9 |6| 5 6] Multiply 6 * 4(previus row and same index)
 [8 6 |4| 4 3] Multiply 4 * 6(previus row and same index)
 [2 4 |2| 9 4] Multiply 2 * 4(previus row and same index)
]

to this:

array a = [
 [4 6 |1 | 5 9]
 [7 9 |4 | 5 9] 
 [8 9 |24| 5 6] 
 [8 6 |24| 4 3] 
 [2 4 |8 | 9 4] 
]

CodePudding user response:

As S3DEV pointed out, you can take slices of your numpy arrays. So for example, let's take your array

a = np.array([[4, 6, 1, 5, 9],
              [7, 9, 4, 5, 9],
              [8, 9, 6, 5, 6],
              [8, 6, 4, 4, 3],
              [2, 4, 2, 9, 4]])

We can take all but the last row with a[:-1,:] and all but the first row with a[1:,:] so you can do your multiplication with b = a[:-1,:] * a[1:,:], giving

[[28 54  4 25 81]
 [56 81 24 25 54]
 [64 54 24 20 18]
 [16 24  8 36 12]]

If you wanted only one column, then like the one you are showing in your example, you could slice further: b = a[:-1,2] * a[1:,2] gives [ 4 24 24 8], or as described in your example [1 * 4, 4 * 6, 6 * 4, 4 * 2].

EDIT: (and hat-tip to Ali_Sh for noticing) To insert something like this directly into your existing numpy.array as you show in your question, you could just do something like a[1:,2] *= a[:-1,2] giving a as:

[[ 4  6  1  5  9]
 [ 7  9  4  5  9]
 [ 8  9 24  5  6]
 [ 8  6 24  4  3]
 [ 2  4  8  9  4]]
  • Related