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
- Installing NumPy in Python
- Creating NumPy Arrays
- NumPy Array Indexing
- NumPy Basic Operations
- NumPy ufuncs
- NumPy Sorting Arrays
Key Features of NumPy
NumPy has various features that make it popular over lists.
- **N-Dimensional Arrays: NumPy’s core feature is
ndarray
, a powerful N-dimensional array object that supports homogeneous data types. - **Arrays with High Performance: Arrays are stored in contiguous memory locations, enabling faster computations than Python lists(Please see Numpy Array vs Python List for details).
- Broadcasting: This allows element-wise computations between arrays of different shapes. It simplifies operations on arrays of **various shapes by automatically aligning their dimensions without creating new data.
- Vectorization: Eliminates the need for explicit Python loops by applying operations directly on entire arrays.
- **Linear algebra: NumPy contains routines for linear algebra operations, such as matrix multiplication, decompositions, and determinants.
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
- **Using ndarray : The array object is called ndarray. NumPy arrays are created using the array() function.
**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]]]
- **Using Numpy Functions: NumPy provides convenient methods to create arrays initialized with specific values like zeros and ones:
**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]
- You can also refer to this article – Different ways to create numpy arrays
**NumPy Array Indexing
Knowing the basics of NumPy array indexing is important for analyzing and manipulating the array object.
- **Basic Indexing: Basic indexing in NumPy allows you to access elements of an array using indices.
**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
- **Slicing: Just like lists in Python, NumPy arrays can be sliced. As arrays can be multidimensional, you need to specify a slice for each dimension of the array.
**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]
- **Advanced Indexing: Advanced Indexing in NumPy provides more powerful and flexible ways to access and manipulate array elements.
**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.
- **Element-wise Operations: We can perform arithmetic operations like addition, subtraction, multiplication, and division directly on NumPy arrays.
**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 ]
- **Unary Operation: These operations are applied to each individual element in the array, without the need for multiple arrays (as in binary operations).
**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]
- **Binary Operators: Numpy Binary Operations apply to the array elementwise and a new array is created. We can use all basic arithmetic operators like +, -, /, etc. In the case of +=, -=, = operators, the existing array is modified.
**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: