numpy
  1. numpy-ndarray

Ndarray

In NumPy, ndarray or N-dimensional array is a fundamental object that is used for storing and manipulating large collections of homogeneous data. The array is an object that is capable of holding a fixed number of items, where each item is of the same type. NumPy provides a large library of mathematical and statistical functions that can be directly applied to these arrays, making them an extremely powerful tool for scientific computing.

Syntax

The syntax for creating an ndarray is as follows:

import numpy as np
# create a 1D array
arr1 = np.array([1, 2, 3, 4, 5])
# create a 2D array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])

Example

Here's an example of how to create and manipulate a simple 1D array, using ndarray in NumPy:

import numpy as np

# create a 1D array
arr = np.array([2, 4, 6, 8, 10])

# print the array
print(arr)

# print the data type of the array
print(arr.dtype)

# print the shape of the array
print(arr.shape)

Output:

[ 2  4  6  8 10]
int64
(5,)

Explanation

In the above example, a 1D array is created using the np.array() method and assigned to the variable arr. The print() function is used to display the contents of the arr variable. The dtype attribute displays the data type of the array and the shape attribute shows the dimension of the array.

Use

ndarray in NumPy provides an efficient way to store and manipulate large collections of homogeneous data. You can use it for various scientific computing tasks such as data analysis, image processing, signal processing, and machine learning.

Important Points

  • Numpy arrays can be created using np.array().
  • The shape of an array can be retrieved using the shape attribute.
  • The data type of an array can be retrieved using the dtype attribute.
  • The size of an array can be retrieved using the size attribute.

Summary

ndarray in NumPy is a fundamental object that is used for storing and manipulating large collections of homogeneous data. It provides an efficient way to store and perform mathematical and statistical operations on large datasets. NumPy's ndarray is an essential tool for scientific computing and machine learning.

Published on: