Transpose and unpack?

a, b = foo().T

>>> a, b = np.arange(20).reshape(-1, 2).T
>>> a
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])
>>> b
array([ 1,  3,  5,  7,  9, 11, 13, 15, 17, 19])
Answer from Moses Koledoye on Stack Overflow
🌐
Educative
educative.io › answers › how-to-split-a-2d-array-in-numpy
How to split a 2D array in Numpy
An array needs to explicitly import the array module for declaration. A 2D array is simply an array of arrays. The numpy.array_split() method in Python is used to split a 2D array into multiple sub-arrays of equal size.
Discussions

How to split a 2d array into multiple 1d arrays?
How to split a 2d array into multiple 1d arrays? In python, a 2d array is already that, it is a 1 dimensional list where every item is another list. Or additionally, rearrange a 2d array so that it is in the form of a grid, so the first group of data in the array is in the first row, and the second in the second etc. Again, you'd have to be more specific, because this is how 2d arrays already are. example = [[1,2,3],[4,5,6],[7,8,9]] example[0] - first row will contain [1,2,3] example[0][1] - acts as a matrix will point to 2 More on reddit.com
🌐 r/learnpython
2
1
January 29, 2019
Split a 2d NumPy array into 2 separate 2d arrays based on a column value
np.split isn't doing what you think it's doing and you don't need it for this. To split an original array x into two subarrays a and b the way you want, you can simply do this: x = np.array([[1, 2, 4], [1, 4, 4], [2, 2, 4], [2, 5, 9]]) a = x[x[:, 0] == 1] b = x[x[:, 0] == 2] More on reddit.com
🌐 r/AskProgramming
2
1
October 19, 2020
Splitting a 2 dimensional array or a list into two 1 dimensional lists in python - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
March 9, 2017
Python: how to split 2d array into many small - Stack Overflow
I want to split my 10x10 array into small 2x2 arrays. I was trying to use itertools.product() but nothing worked correctly. Also, I am not going to use numpy. More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 12
110

There was another question a couple of months ago which clued me in to the idea of using reshape and swapaxes. The h//nrows makes sense since this keeps the first block's rows together. It also makes sense that you'll need nrows and ncols to be part of the shape. -1 tells reshape to fill in whatever number is necessary to make the reshape valid. Armed with the form of the solution, I just tried things until I found the formula that works.

You should be able to break your array into "blocks" using some combination of reshape and swapaxes:

def blockshaped(arr, nrows, ncols):
    """
    Return an array of shape (n, nrows, ncols) where
    n * nrows * ncols = arr.size

    If arr is a 2D array, the returned array should look like n subblocks with
    each subblock preserving the "physical" layout of arr.
    """
    h, w = arr.shape
    assert h % nrows == 0, f"{h} rows is not evenly divisible by {nrows}"
    assert w % ncols == 0, f"{w} cols is not evenly divisible by {ncols}"
    return (arr.reshape(h//nrows, nrows, -1, ncols)
               .swapaxes(1,2)
               .reshape(-1, nrows, ncols))

turns c

np.random.seed(365)
c = np.arange(24).reshape((4, 6))
print(c)

[out]:
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]

into

print(blockshaped(c, 2, 3))

[out]:
[[[ 0  1  2]
  [ 6  7  8]]

 [[ 3  4  5]
  [ 9 10 11]]

 [[12 13 14]
  [18 19 20]]

 [[15 16 17]
  [21 22 23]]]

I've posted an inverse function, unblockshaped, here, and an N-dimensional generalization here. The generalization gives a little more insight into the reasoning behind this algorithm.


Note that there is also superbatfish's blockwise_view. It arranges the blocks in a different format (using more axes) but it has the advantage of (1) always returning a view and (2) being capable of handling arrays of any dimension.

2 of 12
8

It seems to me that this is a task for numpy.split or some variant.

e.g.

a = np.arange(30).reshape([5,6])  #a.shape = (5,6)
a1 = np.split(a,3,axis=1) 
#'a1' is a list of 3 arrays of shape (5,2)
a2 = np.split(a, [2,4])
#'a2' is a list of three arrays of shape (2,5), (2,5), (1,5)

If you have a NxN image you can create, e.g., a list of 2 NxN/2 subimages, and then divide them along the other axis.

numpy.hsplit and numpy.vsplit are also available.

🌐
W3Schools
w3schools.com › python › numpy › numpy_array_split.asp
NumPy Splitting Array
Splitting is reverse operation of Joining. Joining merges multiple arrays into one and Splitting breaks one array into multiple.
Find elsewhere
🌐
Kanoki
kanoki.org › 2020 › 06 › 11 › how-to-split-numpy-arrays
How to split Numpy Arrays | kanoki
June 11, 2020 - array: An ndarray object for partition indices_or_sections: int or 1D array axis: the axis along which to split ... Next we will pass a 1-D array for partition of x i.e. list of indices along which Array to be divided into sub-arrays ... 2nd Partition: Index 1 to 2 along axis = 0 between 1st and 3rd element in indices list array([0,1,2,3]) 3rd Partition: Index 3 to 3 along axis = 0 between 3rd element of indices list and last index of 2D array i.e.
🌐
Interactive Brokers
interactivebrokers.com › campus › ibkr-quant-news › python-split-a-2d-array-vertically-and-convert-it-into-a-3d-array
Python: Split a 2d Array Vertically and Convert It into a 3d Array | IBKR Campus US
May 10, 2023 - # slice vertically 2d array and convert them to 3d array import numpy as np m = np.array([[ 1, 2, 3, 4, 5, 6], [11,12,13,14,15,16], [21,22,23,24,25,26], [31,32,33,34,35,36], [41,42,43,44,45,46]]) m · array([[ 1, 2, 3, 4, 5, 6], [11, 12, 13, 14, 15, 16], [21, 22, 23, 24, 25, 26], [31, 32, 33, 34, 35, 36], [41, 42, 43, 44, 45, 46]]) The following code examples split m (2d array) vertically into 2, 3, or 6 sub 2d arrays and concatenate them as a 3d array.
🌐
Reddit
reddit.com › r/askprogramming › split a 2d numpy array into 2 separate 2d arrays based on a column value
r/AskProgramming on Reddit: Split a 2d NumPy array into 2 separate 2d arrays based on a column value
October 19, 2020 -

So I have this 2d array that looks something like this

[[1,2,4],[1,4,4],[2,2,4],[2,5,9]]

The first column in this array can only ever be a 1 or a 2, I want to split this 2d array into 2 smaller 2d arrays, with all the arrays where the first column equals 1 are in and another where all the arrays whos column 1 has 2 in it. I am new to numpy and have seen some examples and documents online but i can't seem to get exactly what I want. Here is the current code I am trying to use

```

np.split(trainingData, np.where(trainingData[:, 0]== 1.)[0][1:])

```

I am basically trying to split the trainingData(which is my array) into 2 separate arrays, but when I run this I get more than 2 arrays. If someone could point me on the right path that would be great!

Thank you

🌐
YouTube
youtube.com › computer science tutorials
Slice or split 2D array python GCSE Computer Science - YouTube
How to split or slice a 2D array and out the contents into two arrays using iteration in Python.
Published: January 28, 2022
Views: 244
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.hsplit.html
numpy.hsplit — NumPy v2.5 Manual
Please refer to the split documentation. hsplit is equivalent to split with axis=1, the array is always split along the second axis except for 1-D arrays, where it is split at axis=0.
🌐
GeeksforGeeks
geeksforgeeks.org › slice-a-2d-array-in-python
Slice a 2D Array in Python - GeeksforGeeks
March 11, 2024 - Below are some of the ways by which we can slice a 2D array in Python: Basic Slicing · Using List Comprehension · Using np.split() Method · Using Itertools Module · In this example, matrix[0:2] selects the first and second rows, and [1:3] ...
🌐
Stack Overflow
stackoverflow.com › questions › 44487977 › python-how-to-split-2d-array-into-many-small
Python: how to split 2d array into many small - Stack Overflow
I want to split my 10x10 array into small 2x2 arrays. I was trying to use itertools.product() but nothing worked correctly. Also, I am not going to use numpy. Here is the code: ar = [[1,2,3,4], ...
Top answer
1 of 3
3

You're probably looking for something like numpy.reshape.

In your example:

numpy.array([[1,2,3,4], [5,6,7,8]]).reshape(2,4)
>>>array([[1,2], [3,4], [5,6], [7,8]])

Or, as suggested by @MSeifert, using -1 as final dimension will let numpy do the division by itself:

numpy.array([[1,2,3,4], [5,6,7,8]]).reshape(2,-1)
>>>array([[1,2], [3,4], [5,6], [7,8]])
2 of 3
2

To get your desired output, you need to reshape to a 3D array and then unpack the first dimension:

>>> inp = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
>>> list(inp.reshape(-1, 2, 2))
[array([[1, 2],
        [3, 4]]), 
 array([[5, 6],
        [7, 8]]), 
 array([[ 9, 10],
        [11, 12]]), 
 array([[13, 14],
        [15, 16]])]

You can also unpack using = if you want to store the arrays in different variables instead of in one list of arrays:

>>> out1, out2, out3, out4 = inp.reshape(-1, 2, 2)
>>> out1
array([[1, 2],
       [3, 4]])

If you're okay with a 3D array containing your 2D 2x2 arrays you don't need unpacking or the list() call:

>>> inp.reshape(-1, 2, 2)
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]],

       [[13, 14],
        [15, 16]]])

The -1 is a special value for reshape. As the documentation states:

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.


If you want it more general, just take the square root of the row-length and use that as argument for reshape:

>>> inp = np.ones((8, 8))  # 8x8 array
>>> square_shape = 2
>>> inp.reshape(-1, square_shape, square_shape)  # 16 2x2 arrays

>>> square_shape = 4
>>> inp.reshape(-1, square_shape, square_shape)  # 4 4x4 arrays
🌐
GeeksforGeeks
geeksforgeeks.org › splitting-arrays-in-numpy
Splitting Arrays in NumPy - GeeksforGeeks
December 22, 2023 - Similar concepts can be applied to numpy.array_split for uneven splitting. numpy.split ( array, 3, axis=1 ) splits the array into three equal parts along the second axis. Python3 ·
🌐
Stack Overflow
stackoverflow.com › questions › 52721752 › how-to-split-into-a-2-dimensional-array-python › 52721882
How to split into a 2-dimensional array python - Stack Overflow
I want to split the lines in a file into 2 separate (2-dimensional) array. E.g. Username : password array (users[user][pass]) This is the code I have come up with so far : with open('userlist....