# How to Split a 2D Array in Python?

Estimated read time 1 min read

To split a 2D array in Python, you can use slicing to extract a portion of the array as a new array. Here’s an example:

``````import numpy as np

# Create a 2D array
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

# Split the array vertically into two parts
arr1 = arr[:, :2]
arr2 = arr[:, 2:]

# Split the array horizontally into two parts
arr3 = arr[:2, :]
arr4 = arr[2:, :]

# Print the resulting arrays
print(arr1)
print(arr2)
print(arr3)
print(arr4)``````

In this code, the `numpy` module is used to create a 2D array `arr`. The array is then split vertically into two parts using the `:` operator to select all rows and `:2` and `2:` to select the first two and last two columns, respectively. The array is also split horizontally into two parts using `[:2, :]` and `[2:, :]` to select the first two and last two rows, respectively. The resulting arrays are stored in `arr1`, `arr2`, `arr3`, and `arr4`, and printed to the console.

This will output:

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

You can customize the code by modifying the array dimensions, the slicing indices, and the output variable names based on your specific needs.

Add yours