Home > Blockchain >  Numpy array inverse and join
Numpy array inverse and join

Time:04-25

I have this bumpy 2d array and want to reverse it and add it after each item to the original file:

arr =
[[1,2],
[3,4],
[5,6]]

arr2 =
[[1,2],
[2,1],
[3,4],
[4,3],
[5,6],
[6,5]]

CodePudding user response:

If it's a numpy array, you could stack them depth-wise and reshape it:

out = np.dstack([arr, arr[:, [1,0]]]).reshape(-1,2)

Output:

array([[1, 2],
       [2, 1],
       [3, 4],
       [4, 3],
       [5, 6],
       [6, 5]])

CodePudding user response:

This code may help you

arr =[[1,2],
[3,4],
[5,6]]

new_arr = []
for a in arr:
    new_arr.append(a)
    new_arr.append(list(reversed(a)))
print(new_arr)

This is more advance way

arr =[[1,2],
[3,4],
[5,6]]

new_arr = [x for a in arr for x in [a, a[::-1]]]

print(new_arr)

This code works for both python list or numpy array

There is only a minor change in code.

import numpy as np
arr =np.array([[1,2],
[3,4],
[5,6]])

new_arr = [x for a in arr for x in [a, a[::-1]]]

new_arr = np.array(new_arr) # edited

  • Related