NumPy Introduction (original) (raw)

Last Updated : 28 Jan, 2025

**NumPy(Numerical Python) is a fundamental library for Python **numerical computing. It provides efficient multi-dimensional array objects and various mathematical functions for handling large datasets making it a critical tool for professionals in fields that require heavy computation.

Table of Content

Key Features of NumPy

NumPy has various features that make it popular over lists.

Installing NumPy in Python

To begin using NumPy, you need to install it first. This can be done through pip command:

**pip install numpy

Once installed, import the library with the alias np

import numpy as np

Creating NumPy Arrays

**Example:

Python `

import numpy as np

Creating a 1D array

x = np.array([1, 2, 3])

Creating a 2D array

y = np.array([[1, 2], [3, 4]])

Creating a 3D array

z = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print(x) print(y) print(z)

`

Output

[1 2 3] [[1 2] [3 4]] [[[1 2] [3 4]]

[[5 6] [7 8]]]

**Example:

Python `

import numpy as np

a1_zeros = np.zeros((3, 3)) a2_ones = np.ones((2, 2)) a3_range = np.arange(0, 10, 2)

print(a1_zeros) print(a2_ones) print(a3_range)

`

Output

[[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] [[1. 1.] [1. 1.]] [0 2 4 6 8]

**NumPy Array Indexing

Knowing the basics of NumPy array indexing is important for analyzing and manipulating the array object.

**Example:

Python `

import numpy as np

Create a 1D array

arr1d = np.array([10, 20, 30, 40, 50])

Single element access

print("Single element access:", arr1d[2])

Negative indexing

print("Negative indexing:", arr1d[-1])

Create a 2D array

arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

Multidimensional array access

print("Multidimensional array access:", arr2d[1, 0])

`

Output

Single element access: 30 Negative indexing: 50 Multidimensional array access: 4

**Example:

Python `

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]]) #elements from index 1 to 3 print("Range of Elements:",arr[1:4])

#all rows, second column print("Multidimensional Slicing:", arr[:, 1])

`

Output

Range of Elements: [[4 5 6]] Multidimensional Slicing: [2 5]

**Example:

Python `

import numpy as np arr = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

Integer array indexing

indices = np.array([1, 3, 5]) print ("Integer array indexing:", arr[indices])

boolean array indexing

cond = arr > 0 print ("\nElements greater than 0:\n", arr[cond])

`

Output

Elements at indices (0, 3), (1, 2), (2, 1),(3, 0): [4. 6. 0. 3.]

Elements greater than 0: [2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ]

**NumPy Basic Operations

Element-wise operations in NumPy allow you to perform mathematical operations on each element of an array individually, without the need for explicit loops.

**Example:

Python `

import numpy as np

x = np.array([1, 2, 3]) y = np.array([4, 5, 6])

Addition

add = x + y
print("Addition:",add)

Subtraction

subtract = x - y print("substration:",subtract)

Multiplication

multiply = x * y print("multiplication:",multiply)

Division

divide = x / y
print("division:", divide)

`

Output

Addition: [5 7 9] substration: [-3 -3 -3] multiplication: [ 4 10 18] division: [0.25 0.4 0.5 ]

**Example:

Python `

import numpy as np

Example array with both positive and negative values

arr = np.array([-3, -1, 0, 1, 3])

Applying a unary operation: absolute value

result = np.absolute(arr) print("Absolute value:", result)

`

Output

Absolute value: [3 1 0 1 3]

**Example:

Python `

import numpy as np

Two example arrays

arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6])

Applying a binary operation: addition

result = np.add(arr1, arr2)

print("Array 1:", arr1) print("Array 2:", arr2) print("Addition Result:", result)

`

Output

Array 1: [1 2 3] Array 2: [4 5 6] Addition Result: [5 7 9]

**NumPy ufuncs

NumPy provides familiar mathematical functions such as **sin, cos, exp, etc. These functions also operate elementwise on an array, producing an array as output.

**Example:

Python `

import numpy as np

create an array of sine values

a = np.array([0, np.pi/2, np.pi]) print ("Sine values of array elements:", np.sin(a))

exponential values

a = np.array([0, 1, 2, 3]) print ("Exponent of array elements:", np.exp(a))

square root of array values

print ("Square root of array elements:", np.sqrt(a))

`

**Output:

Sine values of array elements: [ 0.00000000e+00 1.00000000e+00 1.22464680e-16] Exponent of array elements: [ 1. 2.71828183 7.3890561 20.08553692] Square root of array elements: [ 0. 1. 1.41421356 1.73205081]

**NumPy Sorting Arrays

We can use a simple **np.sort() method for sorting Python NumPy arrays.

**Example:

Python `

import numpy as np

set alias names for dtypes

dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]

Values to be put in array

values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7), ('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]

Creating array

arr = np.array(values, dtype = dtypes) print ("\nArray sorted by names:\n", np.sort(arr, order = 'name'))

print ("Array sorted by graduation year and then cgpa:\n", np.sort(arr, order = ['grad_year', 'cgpa']))

`

Output

Array sorted by names: [(b'Aakash', 2009, 9. ) (b'Ajay', 2008, 8.7) (b'Hrithik', 2009, 8.5) (b'Pankaj', 2008, 7.9)] Array sorted by graduation year and then cgpa: [(b'Pankaj', 2008, 7.9) (b'Ajay',...

**Read More: