NumPy Joining and Splitting Arrays

Lesson 10 of 17

Joining puts several arrays together into one; splitting breaks one array into several. Both come up all the time when you combine or batch data.

Join with concatenate()

Example

Python
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.concatenate((a, b)))

Output

Plain Text
[1 2 3 4 5 6]

For 2-D arrays the axis argument chooses the direction: axis=0 adds rows, axis=1 adds columns.

Example

Python
import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

print(np.concatenate((a, b), axis=0))
print(np.concatenate((a, b), axis=1))

Output

Plain Text
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
[[1 2 5 6]
 [3 4 7 8]]

stack(), hstack() and vstack()

stack() joins arrays along a new axis. hstack() joins them side by side and vstack() puts one on top of the other.

Example

Python
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print(np.stack((a, b)))
print(np.hstack((a, b)))
print(np.vstack((a, b)))

Output

Plain Text
[[1 2 3]
 [4 5 6]]
[1 2 3 4 5 6]
[[1 2 3]
 [4 5 6]]

Split with array_split()

Example

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
parts = np.array_split(arr, 3)

print(parts[0], parts[1], parts[2])

Output

Plain Text
[1 2] [3 4] [5 6]

If the array does not divide evenly, array_split() makes some parts one element shorter. The stricter np.split() raises an error instead.

Example

Python
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])
for part in np.array_split(arr, 3):
    print(part)

Output

Plain Text
[1 2 3]
[4 5]
[6 7]

Split a 2-D array

Example

Python
import numpy as np

arr = np.arange(1, 13).reshape(4, 3)
top, bottom = np.array_split(arr, 2)

print(top)
print(bottom)

Output

Plain Text
[[1 2 3]
 [4 5 6]]
[[ 7  8  9]
 [10 11 12]]