Curriculum
Course: Mastering NumPy
Login
Text lesson

Reshaping NumPy Array

In this lesson, you will learn

  • Introduction
  • Reshaping NumPy Array
  • Flattening Arrays

 

Introduction

  • Data manipulation with NumPy arrays involves performing various operations on arrays to transform, reshape, filter, and manipulate the data.
  • NumPy provides a rich set of functions for such operations, making it a powerful tool for data manipulation tasks.

Let’s explore some common data manipulation operations with NumPy arrays:

 

One-dimensional arrays can be reshaped, indexed, sliced, and iterated over, much like lists and other Python sequences

 

1. Reshaping Arrays:

numpy.reshape(a, newshape): Gives a new shape to an array without changing its data.

 

Example

import numpy as np

arr = np.arange(1, 10)
reshaped_arr = np.reshape(arr, (3, 3))

print(reshaped_arr)

 

Output

[[1 2 3]
 [4 5 6]
 [7 8 9]]

 

2. Flattening Arrays:

numpy.flatten(order='C'): Returns a copy of the array collapsed into one dimension.

Parameters: order: {‘C’, ‘F’, ‘A’, ‘K’}, optional

‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order in which the elements occur in memory. The default is ‘C’.

 

Example-1

import numpy as np

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

print(flattened_arr)

 

Output

[1 2 3 4 5 6]

 

Example-2

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
flattened_arr = arr.flatten('F')

print(flattened_arr)

 

Output

[1 4 2 5 3 6]

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review