Numpy Array Reshaping Part – 2

To split an array into multiple sub-arrays vertically, you can use the np.vsplit() function. Here’s an example:

import numpy as np

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

sub_arrays = np.vsplit(arr, 2)

print(sub_arrays)
# Output:
# [array([[1, 2, 3],
#         [4, 5, 6]]),
#  array([[ 7,  8,  9],
#         [10, 11, 12]])]

In this example, we split the array arr into two sub-arrays vertically.

To split an array into multiple sub-arrays horizontally, you can use the np.hsplit() function. Here’s an example:

import numpy as np

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

sub_arrays = np.hsplit(arr, 3)

print(sub_arrays)
# Output:
# [array([[1],
#         [4],
#         [7]]),
#  array([[2],
#         [5],
#         [8]]),
#  array([[3],
#         [6],
#         [9]])]

In this example, we split the array arr into three sub-arrays horizontally.

To give a new shape to a masked array without changing its data, you can use the .reshape() method. Here’s an example:

import numpy as np

arr = np.ma.array([1, 2, 3, 4, 5, 6], mask=[0, 0, 0, 1, 1, 1])

new_shape = (2, 3)

reshaped_arr = arr.reshape(new_shape)

print(reshaped_arr)
# Output:
# [[1 2 3]
#  [-- -- --]]

In this example, we reshape the masked array arr to a new shape of (2, 3), keeping the masked values unchanged.

To squeeze the size of a matrix, you can use the np.squeeze() function. Here’s an example:

import numpy as np

arr = np.array([[[1]], [[2]], [[3]]])

squeezed_arr = np.squeeze(arr)

print(squeezed_arr)
# Output: [1 2 3]

In this example, we squeeze the size of the matrix arr by removing the singleton dimensions, resulting in a 1-dimensional array.

Run Code In Live & Test

Leave a Reply

Your email address will not be published. Required fields are marked *