DS31032023 - Assignment Questions

Hello learners,

Q1. Explain with code the difference between NumPy reshape() and resize()
Q2. Explain with code the difference between NumPy flattern() and ravel()
Q3. Explain hsplit() and vsplit() NumPy functions with examples.

2 Likes

A1. ## Reshaping arrays

Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.

By reshaping we can add or remove dimensions or change number of elements in each dimension.

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)

Reshaped_array : ndarray - The new array is formed from the data in the old array,

repeated if necessary to fill out the required number of elements.

The data are repeated in the order that they are stored in memory.

#Example: Resizing a NumPy array using numpy.resize()

import numpy as np
a = np.array([[1,2], [3,4]])
np.resize(a, (3,2))
array([[1, 2],
[3, 4],
[1, 2]])

A2.
ravel():

  1. Returns only the reference/view of the original array
  2. In the event that we alter the array, we will be able to see that the value of the original array changes too.
  3. Ravel is faster than flatten() because it doesn’t take up any memory.
  4. Ravel is a library-level function at the library level.

flatten():

  1. Return a duplicate of the initial array
  2. When you alter the value of this array, the original array’s value is not changed.
  3. Flatten() is considerably faster that ravel() because it takes up memory.
  4. Flatten is a method used by a ndarray.

Flatten
arr4 = np.arange(3,15).reshape(4,3)
arr4

Output:
array([[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])

arr4_flattened = arr4.flatten()
arr4_flattened

Output:
array([ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

Ravel
arr4 = np.arange(3, 15).reshape(4, 3)
arr4

Output:
array([[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14]])

arr4_raveled = arr4.ravel()
arr4_raveled

Output:
array([ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

A3.
import numpy as np
arr6 = np.arange(9).reshape(3,3)

arr6
output :
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])

np.vsplit(arr6, 3)
output: [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]

np.hsplit(arr6, 3)
output:
[array([[0],
[3],
[6]]),
array([[1],
[4],
[7]]),
array([[2],
[5],
[8]])]