Python Forum
reshaping 2D numpy array - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: reshaping 2D numpy array (/thread-39101.html)



reshaping 2D numpy array - paul18fr - Jan-01-2023

Hi

Does somebody have a more efficient way to reshape the following M matrix?

The only way i've found so far is to extract 2 intermediate matrixes before concatenating them, but I'm persuaded one can do it in a more elegant way.

Thanks for any advice

Paul
import numpy as np

M = np.array([[0, 0, -1],   # P1
              [0, 0, -1], 
              [0, 0, 0], 
              [0, 0, 0],    # P2
              [0, 0, 1],
              [0, 0, 1]])

r, c = np.shape(M) 
k = 2

Target = np.array([[0, 0, -1, 0, 0, 0, 0, 0, 1],
                   [0, 0, -1, 0, 0, 0, 0, 0, 1]])

# M1 = M.reshape(k, c*(r//k))
# Test1 = np.array_equal(Target, M1)

# M2 = M.reshape(k, c*(r//k), order='C')
# Test2 = np.array_equal(Target, M2)

# M3 = M.reshape(k, c*(r//k), order='F')
# Test3 = np.array_equal(Target, M3)

# M4 = M.reshape(k, c*(r//k), order='A')
# Test4 = np.array_equal(Target, M4)

i = np.arange(0, r, k)
j = np.arange(1, r, k)
M5 = np.vstack((M[i, :].reshape(1, (r*c//k)), M[j, :].reshape(1, (r*c//k))))

Test5 = np.array_equal(Target, M5)
print(f"M5 = {M5}")
print(f"Test5 = {Test5}")



RE: reshaping 2D numpy array - Larz60+ - Jan-01-2023

>>> import numpy as np
>>> M = np.array([
...               [0, 0, -1],   # P1
...               [0, 0, -1], 
...               [0, 0, 0], 
...               [0, 0, 0],    # P2
...               [0, 0, 1],
...               [0, 0, 1]
... ])
>>> r, c = np.shape(M) 
>>> X = np.reshape(M, (r,c))
>>> Target = np.reshape(X, (2,9))
>>> Target
array([[ 0,  0, -1,  0,  0, -1,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  1,  0,  0,  1]])
>>>
EDIT: Sorry, This is not correct!


RE: reshaping 2D numpy array - perfringo - Jan-01-2023

You can grab indices and using vstack and ravel get desired result:

import numpy as np

arr = np.array([[0, 0, -1],   
              [0, 0, -1], 
              [0, 0, 0], 
              [0, 0, 0],    
              [0, 0, 1],
              [0, 0, 1]])

arr_2 = np.vstack((arr[::2].ravel(), arr[1::2].ravel()))

# arr_2
[[ 0  0 -1  0  0  0  0  0  1]
 [ 0  0 -1  0  0  0  0  0  1]]
But this feels too brute-force. Therefore alternative could be preferred:

arr_3 = arr.reshape(-1, 2, 3).swapaxes(0, 1).reshape(2, -1)



RE: reshaping 2D numpy array - paul18fr - Jan-03-2023

Thanks for all replies.

@Perfringo: interesting solution using 3D arrays; i'll do tests and metrics to figure out how it works and how I can use it for huge arrays

Paul