Skip to content
Advertisement

Manipulating numpy arrays (concatenating inner sub-arrays)

I have a question of manipulating numpy arrays. Say, given a 3-d array in the form np.array([[[1,2],[3,4]], [[5,6],[7,8]]]) which is a (2,2,2) array. I want to manipulate it into a (2,4) array such that a = np.array([[1,2,5,6],[3,4,7,8]]). I want to know is there any built-in methods of numpy particularly dealing with problems like this and can be easily generalized.

EDITED: Thank you all guys’ answers. They all rock! I thought I should clarify what I mean by “easily generalized” in the original post. Suppose given a (6,3,2,3) array (this is the actual challenge I am facing)

JavaScript

I want to massage it into a (3,3,2,2,3) array such that fora[0,:,:,:,:]

JavaScript

In short, the last 3 biggest blocks should “merge” with first 3 biggest blocks to form 3 (3,2) blocks. The rest of 2 blocks i.e., (a[1,:,:,:,:], a[2,:,:,:,:]) follow the same pattern.

Advertisement

Answer

From your new update, you can do the following using np.lib.stride_tricks.as_strided:

JavaScript

Explanation:

Take another example: a small array q and our desired output after changing q:

JavaScript

Here we are using numpy strides to achieve this. Let’s check for q‘s strides:

JavaScript

In our output, all strides should remain the same, except the third stride, because in the third dimension we need to stack with the values from bottom half of q, ie: 6 is put next to 0, 7 next to 1 and so on…

So, how “far” is it from 0 to 6 ? Or in another word, how far is it from q[0,0,0] to q[2,0,0] ?

JavaScript

Okay then new_strides = (12, 4, 24) and hence we got:

JavaScript

Back to your question:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement