NumPy Basics

NumPy Basics

part-1

Introduction

  • NumPy Stands for Numerical Python

  • Fundamental package for numerical computations in Python

  • General-purpose and array processing package.

why do we use NumPy

  • it provides high performance and works with a multidimensional array

  • In Python, we have lists that serve the purpose of arrays, but they are slow to process.

  • NumPy provides an array object that is up to 50 times faster than traditional Python lists.

Why is NumPy Faster Than Lists?

in NumPy, all elements of an array are placed next to each other in memory whereas in the list each element is a separate object with its memory address in memory

To install NumPy

pip install NumPy

To import NumPy

import NumPy as np

To create a NumPy array

Syntax: NumPy. Array(object)



import numpy as np
X=numpy.array([2,5,6]
print(type(X))
import numpy as np

# Create a 1D NumPy array from a Python list
arr1d = np.array([1, 2, 3, 4, 5])
print("1D array:")
print(arr1d)

# Create a 2D NumPy array from a Python list of lists
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D array:")
print(arr2d)

# Create a 3D NumPy array from a Python list of lists of lists
arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D array:")
print(arr3d)
---OUTPUT----
1D array:
[1 2 3 4 5]

2D array:
[[1 2 3]
 [4 5 6]]

3D array:
[[[1 2]
  [3 4]]
  • arr1d is a 1D NumPy array created from a Python list [1, 2, 3, 4, 5].

  • arr2d is a 2D NumPy array created from a Python list of lists [[1, 2, 3], [4, 5, 6]].

  • arr3d is a 3D NumPy array created from a Python list of lists of lists [[[1, 2], [3, 4]], [[5, 6], [7, 8]]].