Open In App

Numpy - ndarray

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

ndarray((short for N-dimensional array)) is a core object in NumPy. It is a homogeneous array which means it can hold elements of the same data type. It is a multi-dimensional data structure that enables fast and efficient manipulation of large dataset

Let's understand with a simple example:


Output
[1 2 3 4 5]
[[1 2 3]
 [4 5 6]]
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]

Attributes of ndarray

Understanding the attributes of an ndarray is essential to working with NumPy effectively. Here are the key attributes:

  • ndarray.shape: Returns a tuple representing the shape (dimensions) of the array.
  • ndarray.ndim: Returns the number of dimensions (axes) of the array.
  • ndarray.size: Returns the total number of elements in the array.
  • ndarray.dtype: Provides the data type of the array elements.
  • ndarray.itemsize: Returns the size (in bytes) of each element

Example:


Output
Shape: (2, 3)
Dimensions: 2
Size: 6
Data type: int64
Item size: 8

Array Indexing and Slicing

NumPy allows powerful indexing and slicing operations on ndarrays, similar to Python lists but with additional functionality.

  • Basic Indexing: we can index a single element in an array using square brackets.

Example:

  • Slicing: You can extract sub-arrays using slicing syntax.

Output
[20 30 40]
  • Multi-dimensional Indexing: In multi-dimensional arrays, you can index and slice each dimension separately.

Example:


Output
6
[[2 3]
 [5 6]]

Array Operations

These operations allow you to perform element-wise arithmetic or other operations on entire arrays without the need for explicit loops.

  • Element-wise Operations:

Output
[5 7 9]
[ 4 10 18]
[-3 -3 -3]
[0.25 0.4  0.5 ]
  • Matrix Operations (Dot product):

Output
[[19 22]
 [43 50]]

Broadcasting

Broadcasting is a powerful feature in NumPy that allows you to perform operations on arrays of different shapes.

Example:


Output
[[11 12]
 [13 14]]

Reshaping and Flattening

NumPy provides functions to reshape or flatten arrays, which is useful when working with machine learning or deep learning algorithms.

  • Reshaping:

Output
[[1 2 3]
 [4 5 6]]
  • Flattening: Convert multi-dimensional arrays into one-dimensional arrays.

Output
[1 2 3 4 5 6]

Next Article
Article Tags :

Similar Reads