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.

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

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)

#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():

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

flatten():

- Return a duplicate of the initial array
- When you alter the value of this array, the original array’s value is not changed.
- Flatten() is considerably faster that ravel() because it takes up memory.
- 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]])]