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.

Answer from unutbu on Stack Overflow
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.

Discussions

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
python - Easiest way to split 2d numpy array in to two 1d arrays? - 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
How to turn a string of a 2D array into a 2D array?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
6
0
February 25, 2024
Use numpy array of keys to pull values from dictionary?
Could try itemgetter(): from operator import itemgetter record = {"A":1,"B":2,"C":3,"D":4} group = ['A', 'C'] values = itemgetter(*group)(record) print(values) # (1, 3) More on reddit.com
🌐 r/learnpython
4
2
March 23, 2022
🌐
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.
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_split.asp
NumPy Splitting Array
We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits. ... import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) newarr = np.array_split(arr, 3) print(newarr) Try it Yourself »
🌐
Educative
educative.io › answers › how-to-split-a-2d-array-in-numpy
How to split a 2D array in Numpy
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.
🌐
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.
Find elsewhere
🌐
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

🌐
Data Science Parichay
datascienceparichay.com › home › blog › horizontally split numpy array with hsplit()
Horizontally split numpy array with hsplit() - Data Science Parichay
June 17, 2022 - Just pass axis=1 along with the input array and the number of sections to split it into. Let’s split the above 2d array into two sub-arrays horizontally but using the numpy split() function this time.
🌐
TutorialsPoint
tutorialspoint.com › numpy › numpy_split.htm
Numpy split() Function
Here in this example we show how to split a 2D array into 2 sub-arrays along the columns i.e. axis=1 − · import numpy as np # Create a 2D array arr = np.arange(16).reshape(4, 4) print("Original 2D array:") print(arr) # Split the 2D array into 2 sub-arrays along columns result = np.split(arr, 2, axis=1) print("\nSplit 2D array into 2 sub-arrays along columns:") for i, sub_array in enumerate(result): print(f"Sub-array {i+1}:") print(sub_array) Original 2D array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Split 2D array into 2 sub-arrays along columns: Sub-array 1: [[ 0 1] [ 4 5] [ 8 9] [12 13]] Sub-array 2: [[ 2 3] [ 6 7] [10 11] [14 15]] numpy_array_manipulation.htm ·
🌐
w3resource
w3resource.com › numpy › manipulation › hsplit.php
NumPy: numpy.hsplit() function - w3resource
April 24, 2026 - >>> import numpy as np >>> a = ... 0), dtype=float64)] In the above code the np.hsplit() function is called with the array 'a' and an array of specific indices [3,6]. This will split the array 'a' into three arrays at positions ...
🌐
Note.nkmk.me
note.nkmk.me › home › python › numpy
NumPy: Split an array with np.split, np.vsplit, np.hsplit, etc. | note.nkmk.me
February 6, 2024 - a0, a1 = np.split(a, [10]) print(a0) # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11] # [12 13 14 15]] print(a1) # [] print(type(a1)) # <class 'numpy.ndarray'> ... The axis (dimension) along which to split the array is specified by the third argument, axis. Omitting this argument, as in the examples so far, defaults to axis=0. It is also valid to explicitly specify axis=0, which splits the array along the 0th axis, i.e., by rows in 2D arrays.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.array_split.html
numpy.array_split — NumPy v2.5 Manual
>>> import numpy as np >>> x = np.arange(8.0) >>> np.array_split(x, 3) [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])]
🌐
GeeksforGeeks
geeksforgeeks.org › splitting-arrays-in-numpy
Splitting Arrays in NumPy - GeeksforGeeks
December 22, 2023 - This is where array splitting comes into play, allowing you to break down an array into smaller sub-arrays, making the data more manageable. It is similar to slicing but on a larger scale. NumPy provides various methods that are specifically designed for different use cases and scenarios. Array splitting in NumPy is like a slice of cake.
🌐
Codecademy
codecademy.com › docs › python:numpy › built-in functions › .split()
Python:NumPy | Built-in Functions | .split() | Codecademy
April 4, 2025 - import numpy as np · # Split a 1D array into 3 equal parts · arr = np.array([11, 22, 33, 44, 55, 66]) print(np.split(arr, 3)) # Split a 2D array into 2 parts along rows (axis=0) nd = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) print(np.split(nd, 2, axis=0)) # Split a 2D array at column indices [1, 2] print(np.split(nd, [1, 2], axis=1)) Copy to clipboard ·
🌐
DataCamp
datacamp.com › doc › numpy › split
NumPy split()
Before using any examples, ensure you have imported NumPy: ... This example splits the 1D array `arr` into three equal sub-arrays, each containing two elements: `[1, 2]`, `[3, 4]`, and `[5, 6]`. arr = np.array([10, 20, 30, 40, 50]) result = np.split(arr, [1, 3]) Here, the array `arr` is split at indices 1 and 3, resulting in sub-arrays: `[10]`, `[20, 30]`, and `[40, 50]`. arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) result = np.split(arr, 2, axis=0) This example splits a 2D array `arr` along the first axis into two sub-arrays: `[[1, 2], [3, 4]]` and `[[5, 6], [7, 8]]`.
🌐
Python Tutorial
pythontutorial.net › home › python numpy › numpy split()
NumPy split() - Python Tutorial
August 16, 2022 - Use NumPy split() function to split an array into subarrays.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to split numpy array | using split()
How to Split NumPy Array | Using split() - Spark By {Examples}
March 27, 2024 - How to split an array into multiple arrays in Numpy? In NumPy, the numpy.split() function can be used to split an array into more than one (multiple) sub