NumPy Tutorial · NumPy Tutorial

NumPy Array Split

Learn all about NumPy Array Split in this comprehensive tutorial.

5 min read intermediate
  • Splitting is reverse operation of Joining.
  • The return value of the array_split() method is a list containing each of the split as an array.
  • Use the same syntax when splitting 2-D arrays.

Splitting NumPy Arrays

Splitting is reverse operation of Joining.

Joining merges multiple arrays into one and Splitting breaks one array into multiple.

We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.

python
Note: Note: The return value is a list containing three arrays.

If the array has less elements than required, it will adjust from the end accordingly.

python
Note: Note: We also have the method split() available but it will not adjust the elements when elements are less in source array for splitting like in example above, array_split() worked properly but split() would fail.

Split Into Arrays

The return value of the array_split() method is a list containing each of the split as an array.

If you split an array into 3 arrays, you can access them from the result just like any array element:

python

Splitting 2-D Arrays

Use the same syntax when splitting 2-D arrays.

Use the array_split() method, pass in the array you want to split and the number of splits you want to do.

python

The example above returns three 2-D arrays.

Let's look at another example, this time each element in the 2-D arrays contains 3 elements.

python

The example above returns three 2-D arrays.

In addition, you can specify which axis you want to do the split around.

The example below also returns three 2-D arrays, but they are split along the column (axis=1).

python

An alternate solution is using hsplit() opposite of hstack()

python
Note: Note: Similar alternates to vstack() and dstack() are available as vsplit() and dsplit().

Module quiz

2 questions
1

Which of the following is true about NumPy Array Split?

2

What is the most common pitfall when working with NumPy Array Split?

Answer all questions to submit.