1
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?

1 Answer 1

2

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]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.