An student
An student

Reputation: 392

getting multiple array after performing subtraction operation within array elements

import numpy as np
m = []
k = []
a = np.array([[1,2,3,4,5,6],[50,51,52,40,20,30],[60,71,82,90,45,35]])
for i in range(len(a)):
    m.append(a[i, -1:])
    for j in range(len(a[i])-1):
        n = abs(m[i] - a[i,j])
        k.append(n)
    k.append(m[i])
print(k)

Expected Output in k:

[5,4,3,2,1,6],[20,21,22,10,10,30],[25,36,47,55,10,35]

which is also a numpy array.

But the output that I am getting is

[array([5]), array([4]), array([3]), array([2]), array([1]), array([6]), array([20]), array([21]), array([22]), array([10]), array([10]), array([30]), array([25]), array([36]), array([47]), array([55]), array([10]), array([35])]

How can I solve this situation?

Upvotes: 1

Views: 26

Answers (1)

Kasravnd
Kasravnd

Reputation: 107347

You want to subtract the last column of each sub array from themselves. Why don't you use a vectorized approach? You can do all the subtractions at once by subtracting the last column from the rest of the items and then column_stack together with unchanged version of the last column. Also note that you need to change the dimension of the last column inorder to be subtractable from the 2D array. For that sake we can use broadcasting.

In [71]: np.column_stack((abs(a[:, :-1] - a[:, None, -1]), a[:,-1]))
Out[71]: 
array([[ 5,  4,  3,  2,  1,  6],
       [20, 21, 22, 10, 10, 30],
       [25, 36, 47, 55, 10, 35]])

Upvotes: 2

Related Questions