0% found this document useful (0 votes)
3 views73 pages

Numpy Module

The document provides an overview of the array module in Python, detailing its characteristics, creation, and manipulation of arrays, including type codes and methods. It also introduces the NumPy library, emphasizing its capabilities for numerical and scientific computing, including the creation of ndarrays and their attributes. Key features of both the array module and NumPy, such as memory efficiency and support for mathematical operations, are highlighted.

Uploaded by

vishnumg2003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views73 pages

Numpy Module

The document provides an overview of the array module in Python, detailing its characteristics, creation, and manipulation of arrays, including type codes and methods. It also introduces the NumPy library, emphasizing its capabilities for numerical and scientific computing, including the creation of ndarrays and their attributes. Key features of both the array module and NumPy, such as memory efficiency and support for mathematical operations, are highlighted.

Uploaded by

vishnumg2003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Array Module in Python

An array is a data type used to store multiple values using a single identifier (variable name).
An array contains an ordered collection of data elements where each element is of the same
type and can be referenced by its index (position).
The important characteristics of an array are:
• Each element of the array is of same data type, though the values stored in them may
be different.
• The entire array is stored contiguously in memory. This makes operations on array fast.
• Each element of the array is identified or referred using the name of the Array along
with the index of that element, which is unique for each element. The index of an
element is an integral value associated with the element, based on the element’s
position in the array.
For example consider an array with 5 numbers:
[ 10, 9, 99, 71, 90 ]
Zero based indexing is used to access array elements. For eg. index 0 represents the first
element, 1 represents the second element and so on. Backward indexing starts from -1 at the
last element of the array and decreases by 1 towards the left of the array. This is very similar to
the indexing of lists in Python.

●​ The array module in Python provides an efficient way to store homogeneous data
(all elements of the same type).
●​ It is built -in module to create and manipulate ID (one Dimensional) Arrays.​

●​ It is more memory-efficient than lists but less powerful than NumPy arrays.​

●​ Each array requires a type code (like 'i' for integers, 'f' for floats).

Importing the Module


import array

Creating Arrays

Syntax:

[Link](typecode, initializer)
●​ typecode: A single character code that specifies the type of
array elements.​

●​ initializer: Optional list/tuple to populate the array.​

Example:

import array

arr = [Link]('i', [10, 20, 30, 40])


print(arr)

Output:

array('i', [10, 20, 30, 40])

Type Codes (Attributes)

Typecod C Type Python Size (bytes)


e Type

'b' signed char int 1

'B' unsigned char int 1

'i' signed int int 2 or 4

'I' unsigned int int 2 or 4

'l' signed long int 4

'L' unsigned long int 4

'f' float float 4

'd' double float 8

Attributes of array
arr = [Link]('i', [1,2,3,4])
print([Link]) # 'i' → type of elements
print([Link]) # 4 → bytes per element
print(arr.buffer_info()) # (address, length)
print(len(arr)) # 4

Output:

i
4
(1763652116544, 4)
4

Methods of array

(a) Append
[Link](5)
print(arr) # array('i', [1,2,3,4,5])

(b) Extend
[Link]([6,7])
print(arr) # array('i', [1,2,3,4,5,6,7])

(c) Insert
[Link](1, 99)
print(arr) # array('i', [1,99,2,3,4,5,6,7])

(d) Remove
[Link](3)
print(arr) # array('i', [1,99,2,4,5,6,7])

(e) Pop
x = [Link](2)
print(x) # 2
print(arr) # array('i', [1,99,4,5,6,7])

(f) Index
print([Link](99)) # 1
(g) Reverse
[Link]()
print(arr)

(h) Count
print([Link](5)) # 1

(i) Convert to List


print([Link]()) # [7,6,5,4,99,1]

7. Iteration
for x in arr:
print(x, end=" ")

Output:

7 6 5 4 99 1

Operations on Arrays

(a) Concatenation
a1 = [Link]('i', [1,2,3])
a2 = [Link]('i', [4,5])
a3 = a1 + a2
print(a3) # array('i', [1,2,3,4,5])

(b) Repetition
print(a1 * 2) # array('i', [1,2,3,1,2,3])

(c) Slicing
print(a3[1:4]) # array('i', [2,3,4])
NUMPY Module
NumPy (Numerical Python) is a powerful Python library used for numerical and
scientific computing. It provides support for arrays, matrices, and a collection of
mathematical functions to operate on these data structures efficiently.
Key Features of NumPy:
1.​ N-dimensional Array Object (ndarray): At its core, NumPy provides a
powerful n-dimensional array object that allows for fast and efficient
handling of large datasets.
2.​ Mathematical Functions: NumPy includes a wide variety of built-in
mathematical functions, such as linear algebra operations, Fourier
transforms, and random number generation.
3.​ Broadcasting: It supports broadcasting, allowing operations on arrays of
different shapes without needing to explicitly reshape them.
4.​ Integration with Other Libraries: Many popular scientific computing
libraries like SciPy, pandas, and machine learning frameworks like
TensorFlow rely on NumPy arrays for their underlying data structures.
5.​ Memory Efficiency: Compared to Python lists, NumPy arrays use much less
memory and provide better performance for large datasets.
Advantages of NumPy:
1.​ Performance: NumPy is written in C and Fortran, making it much faster than
native Python for large computations, especially with vectorized operations
(i.e., applying operations on entire arrays instead of using loops).
2.​ Efficient Storage: Arrays in NumPy are stored more efficiently than Python
lists because they use fixed data types (e.g., integers, floats), leading to
lower memory consumption.
3.​ Easy Array Operations: NumPy allows for a wide range of mathematical
operations on arrays, such as element-wise addition, subtraction,
multiplication, and division, without the need for explicit loops. This makes
code simpler and more readable.
4.​ Multi-Dimensional Arrays: It simplifies working with multi-dimensional
arrays (matrices, tensors) and provides built-in functions for reshaping,
splitting, stacking, and transposing arrays.
5.​ Cross-Library Compatibility: NumPy arrays are the standard for numerical
data and are seamlessly integrated with many other Python libraries,
making it easier to switch between different libraries for data analysis and
machine learning.
6.​ Support for Advanced Functions: It includes advanced functions like:
o​ Linear algebra functions: Determinants, eigenvalues, matrix
inversions.
o​ Fourier Transforms: Discrete Fourier transforms.
o​ Random Number Generation: For simulations and probabilistic
computations.
7.​ Data Analysis and Machine Learning: Due to its efficiency and flexibility,
NumPy is used in data science workflows, particularly for pre-processing
data and performing operations before feeding data into machine learning
algorithms.
In summary, NumPy is an essential tool for scientific and numerical computation
in Python, allowing users to perform high-performance operations on large
datasets easily.

ndarray
An ndarray (N-dimensional array) is the fundamental data structure in NumPy
used for scientific and numerical [Link] represents a multi-dimensional,
homogeneous array of fixed-size items. All elements in an ndarray must be of the
same type (e.g., integers, floats), and it supports efficient operations on large
datasets.
It:

1.​ Stores homogeneous elements (all of the same dtype).​


2.​ Can represent multi-dimensional data (1D → vector, 2D → matrix, 3D+ →
tensors).​

3.​ Provides high performance because data is stored in contiguous memory.​

4.​ Supports vectorized operations and broadcasting, avoiding slow Python


loops.​

5.​ Forms the foundation of libraries like Pandas, SciPy, scikit-learn.​

Example:

import numpy as np

arr = [Link]([[1, 2, 3], [4, 5, 6]])

print([Link]) # (2, 3)

print([Link]) # int64

Key Points about ndarray:


●​ Homogeneous: All elements must be of the same type.
●​ Efficient: Provides efficient memory usage and operations compared to
Python lists.
●​ Multi-Dimensional: Easily handles arrays with more than one dimension
(e.g., matrices, tensors).
●​ Vectorized Operations: Supports fast, element-wise operations without the
need for explicit loops.

dtype in NumPy
●​ A dtype (short for data-type object) is a NumPy object that specifies how
data in an ndarray is stored and interpreted. It describes the type and
size of elements stored in a NumPy ndarray.
●​ It defines the type of data (int, float, string, etc.).​

●​ It defines the size in bytes (e.g., i4 = 4-byte int, f8 = 8-byte float).​

●​ It can describe structured data (records with multiple fields).

It ensures all elements in an ndarray have the same type for efficiency.

Values for dtype

Code Type Example

i4 32-bit signed integer 10

f8 64-bit float 3.1416

b Boolean True/False

S10 String of 10 bytes "Alice"

U10 Unicode string of 10 Bytes ू "漢字" "


"बाब" 😊"

Relationship between ndarray and dtype:

●​ ndarray is the foundation of NumPy -The whole container (array of


values).
●​ dtype = blueprint of element [Link] how each element is
stored (e.g., int32, float64, structured record).
●​ type-object = class used to construct [Link] class linked to
dtype (e.g., <class 'numpy.int32'>).
●​ array scalar. It is actual element [Link] element accessed
from the array (e.g., numpy.int32(10)).

Example
import numpy as np
arr = [Link]([1, 2, 3], dtype=np.int32)
print(arr) # [1 2 3]

print([Link]) # int32 (dtype object)

print([Link]) # <class 'numpy.int32'>(type-object)

print(arr[0]) # 1 (array scalar)

print(type(arr[0])) # <class 'numpy.int32'>

Why Use ndarray?

●​ High performance for mathematical and scientific computing.​

●​ Convenient methods for linear algebra, statistics, and


transformations.​

●​ Basis for other scientific libraries like Pandas, SciPy,


scikit-learn.

Attributes and Methods of ndarray


The ndarray object in NumPy comes with various attributes and methods that
make it highly flexible and powerful for numerical computations.
●​ Attributes provide information about the array’s structure (shape, size, data
type, etc.).
●​ Methods allow you to manipulate the array, perform mathematical
operations, and reshape or reorder elements.
Key Attributes of ndarray
1.​ [Link]
o​ Returns the dimensions of the array as a tuple. For a 2D array, this
will be (rows, columns).
o​ Example:
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print([Link]) # Output: (2, 3)
2.​ [Link]
o​ Returns the number of dimensions (axes) of the array.
o​ Example:
print([Link]) # Output: 2
3.​ [Link]
o​ Returns the total number of elements in the array (the product of the
dimensions).
o​ Example:
print([Link]) # Output: 6
4.​ [Link]
o​ Describes the data type of the array's elements (e.g., int32, float64).
o​ Example:
print([Link]) # Output: int64
5.​ [Link]
o​ Returns the size (in bytes) of each element in the array.
o​ Example:
print([Link]) # Output: 8 (because `int64` is 8 bytes)
6.​ [Link]
o​ Total number of bytes consumed by the elements of the array.
o​ Example:
print([Link]) # Output: 48 (6 elements * 8 bytes each)
7.​ ndarray.T
o​ Transposes the array (i.e., swaps rows and columns).
o​ Example:
print(arr.T) # Output: [[1 4] [2 5] [3 6]]
8.​ [Link]
o​ The number of bytes that should be skipped to proceed to the next
element along each dimension.
o​ Example:
print([Link]) # Output: (24, 8)

Create arrays in Numpy


Creating arrays is fundamental to utilizing NumPy effectively. NumPy offers a
variety of methods to create arrays tailored to different needs, ranging from
simple lists to complex multi-dimensional structures filled with specific values or
sequences.
1.​ From Existing Data: Use [Link]() to convert Python lists or tuples into
NumPy arrays.
2.​ With Specific Values: Functions like [Link](), [Link](), [Link](), and
[Link]() allow for initializing arrays with predefined values.
3.​ With Sequences: [Link](), [Link](), and [Link]() help
generate arrays with evenly spaced values.
4.​ Identity and Diagonal Matrices: [Link]() and [Link]() create identity
matrices, useful in linear algebra.
5.​ Random Arrays: Utilize [Link] functions like rand(), randint(), and
randn() to generate arrays with random values for simulations and testing.
1. Creating Arrays from Python Lists or Tuples
The most straightforward way to create a NumPy array is by converting a Python
list or tuple using the [Link]() function.
Example 1.1: From a Python List
Syntax:
arr =[Link](object, dtype=None)
import numpy as np
# Create a 1D array from a list
list_1d = [1, 2, 3, 4, 5]
array_1d = [Link](list_1d)
print("1D Array from List:")
print(array_1d)
Output:
1D Array from List:
[1 2 3 4 5]
Example 1.2: From a Python Tuple
# Create a 2D array from a tuple of tuples
tuple_2d = ((1, 2, 3), (4, 5, 6))
array_2d = [Link](tuple_2d)
print("\n2D Array from Tuple:")
print(array_2d)
Output:
2D Array from Tuple:
[[1 2 3]
[4 5 6]]
Key Points:
●​ The [Link]() function automatically infers the data type (dtype) based on
the input.
●​ The resulting array’s dimensionality (ndim) is determined by the structure
of the input (e.g., lists within lists create multi-dimensional arrays).
2. Creating Arrays with Specific Values
NumPy provides several functions to create arrays filled with specific values like
zeros, ones, or uninitialized values.
2.1. [Link](): Create an Array Filled with Zeros
arr=[Link](shape, dtype=float)
# Create a 3x4 array filled with zeros
zeros_array = [Link]((3, 4))
print("Array of Zeros:")
print(zeros_array)
Output:
Array of Zeros:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
2.2. [Link](): Create an Array Filled with Ones
arr=[Link](shape, dtype=float)
# Create a 2x3 array filled with ones
ones_array = [Link]((2, 3))
print("\nArray of Ones:")
print(ones_array)
Output:
Array of Ones:
[[1. 1. 1.]
[1. 1. 1.]]
2.3. [Link](): Create an Array Filled with a Specific Value
# Create a 2x2 array filled with the value 7
full_array = [Link]((2, 2), 7)
print("\nArray Filled with 7:")
print(full_array)
Output:
Array Filled with 7:
[[7 7]
[7 7]]
2.4. [Link](): Create an Uninitialized Array
arr=[Link](shape, dtype=float)
# Create a 2x3 empty array (values are uninitialized and may appear random)
empty_array = [Link]((2, 3))
print("\nUninitialized Array (Empty):")
print(empty_array)
Output:
Uninitialized Array (Empty):
[[1.12116783e-316 0.00000000e+000 6.93693117e-310]
[6.93693117e-310 6.93693117e-310 6.93693117e-310]]
Note: The values in an empty array are unpredictable and should be overwritten
before use.
3. Creating Arrays with Sequences
When you need arrays with sequences of numbers, NumPy offers several
functions to generate them efficiently.
3.1. [Link](): Create Arrays with Regular Intervals
arr=[Link](start, stop, step, dtype=None)
Similar to Python's built-in range() but returns a NumPy array.
# Create an array from 0 to 9
array_arange = [Link](10)
print("Array using arange:")
print(array_arange)
# Create an array from 1 to 10 with step 2
array_step = [Link](1, 11, 2)
print("\nArray with Step 2:")
print(array_step)
Output:
Array using arange:
[0 1 2 3 4 5 6 7 8 9]
Array with Step 2:
[1 3 5 7 9]
3.2. [Link](): Create Arrays with a Specified Number of Points
arr=[Link](start, stop, num=50)
Generates linearly spaced values between a start and stop value.
# Create 5 linearly spaced numbers between 0 and 1
array_linspace = [Link](0, 1, 5)
print("\nArray using linspace (5 points between 0 and 1):")
print(array_linspace)
Output:
Array using linspace (5 points between 0 and 1):
[0. 0.25 0.5 0.75 1. ]
3.3. [Link](): Create Arrays with Logarithmically Spaced Values
Generates numbers spaced evenly on a log scale.
# Create 4 logarithmically spaced numbers between 10^1 and 10^3
array_logspace = [Link](1, 3, 4)
print("\nArray using logspace (10^1 to 10^3, 4 points):")
print(array_logspace)
Output:
Array using logspace (10^1 to 10^3, 4 points):
[ 10. 46.41588834 215.443469 1000. ]
4. Creating Identity and Diagonal Matrices
4.1. [Link](): Create a 2D Identity Matrix
Creates a 2D array with ones on the diagonal and zeros elsewhere.
# Create a 3x3 identity matrix
identity_matrix = [Link](3)
print("\nIdentity Matrix using eye:")
print(identity_matrix)
Output:
Identity Matrix using eye:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
4.2. [Link](): Similar to [Link]() but only creates square matrices
# Create a 4x4 identity matrix
identity_matrix2 = [Link](4)
print("\nIdentity Matrix using identity:")
print(identity_matrix2)
Output:
Identity Matrix using identity:
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
Key Points:
●​ Both [Link]() and [Link]() create identity matrices, but [Link]() offers
more flexibility with options like setting the diagonal offset.
5. Creating Arrays with Random Values
Random arrays are essential for simulations, testing algorithms, and initializing
weights in machine learning models.
5.1. [Link](): Uniformly Distributed Random Numbers
[Link](size=None)
Generates random numbers in the range [0, 1).
# Create a 2x3 array of random floats between 0 and 1
random_array = [Link](2, 3)
print("\nRandom Array using rand:")
print(random_array)
Possible Output:
Random Array using rand:
[[0.5488135 0.71518937 0.60276338]
[0.54488318 0.4236548 0.64589411]]
5.2. [Link](): Random Integers
Generates random integers within a specified range.
# Create a 3x3 array of random integers between 10 and 50
random_int_array = [Link](10, 50, size=(3, 3))
print("\nRandom Integer Array using randint:")
print(random_int_array)
Possible Output:
Random Integer Array using randint:
[[22 35 16]
[45 12 33]
[17 29 41]]
5.3. [Link](): Normally Distributed Random Numbers
Generates samples from the standard normal distribution (mean=0, std=1).
# Create a 2x2 array of standard normally distributed random numbers
random_normal = [Link](2, 2)
print("\nRandom Normal Array using randn:")
print(random_normal)
Possible Output:
Random Normal Array using randn:
[[ 1.76405235 0.40015721]
[ 0.97873798 2.2408932 ]]
Key Notes:
●​ Use array() when you already have data.​

●​ Use zeros(), ones(), empty() for initialization.​

●​ Use arange() or linspace() for sequences.​

●​ Use random() when you need random samples.

Creating and managing 2d arrays in numpy


Creating and managing 2D arrays is an essential feature of NumPy, as it allows for
handling matrix-like structures efficiently. A 2D array is essentially an array of
arrays, where each element is indexed by two numbers—one for the row and one
for the column. Below is a detailed explanation of how to create, access, and
manipulate 2D arrays in NumPy.
1. Creating 2D Arrays
You can create 2D arrays in various ways, including from lists, tuples, or using
NumPy functions that generate specific patterns of arrays.
1.1. Creating a 2D Array from a List of Lists
You can convert a nested Python list (or tuple) into a 2D array using [Link]().
import numpy as np
# Create a 2D array from a list of lists
list_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
array_2d = [Link](list_2d)
print("2D Array from List:")
print(array_2d)
Output:
2D Array from List:
[[1 2 3]
[4 5 6]
[7 8 9]]
1.2. Creating 2D Arrays with NumPy Functions
NumPy provides several built-in functions for generating arrays with predefined
values.
1.2.1. Using [Link]()
Creates a 2D array filled with zeros.
zeros_2d = [Link]((3, 3))
print("\n2D Array of Zeros:")
print(zeros_2d)
Output:
2D Array of Zeros:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
1.2.2. Using [Link]()
Creates a 2D array filled with ones.
ones_2d = [Link]((2, 4))
print("\n2D Array of Ones:")
print(ones_2d)
Output:
2D Array of Ones:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]
1.2.3. Using [Link]()
Creates a 2D array filled with a specific value.
full_2d = [Link]((3, 3), 7)
print("\n2D Array Filled with 7:")
print(full_2d)
Output:
2D Array Filled with 7:
[[7 7 7]
[7 7 7]
[7 7 7]]
1.2.4. Using [Link]()
Creates an identity matrix (a square 2D array with ones on the diagonal and zeros
elsewhere).
identity_2d = [Link](4)
print("\nIdentity Matrix (2D):")
print(identity_2d)
Output:
Identity Matrix (2D):
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
1.2.5. Using [Link]()
Creates a 2D array of random values between 0 and 1.
random_2d = [Link](2, 3)
print("\n2D Array of Random Values:")
print(random_2d)
Possible Output:
2D Array of Random Values:
[[0.5488135 0.71518937 0.60276338]
[0.54488318 0.4236548 0.64589411]]
1.3. Using [Link]() and [Link]()
You can create a sequence of numbers using [Link]() and reshape them into a
2D array with [Link]().
# Create a 1D array from 0 to 11
array_1d = [Link](12)
# Reshape the 1D array into a 2D array with 3 rows and 4 columns
reshaped_2d = array_1d.reshape((3, 4))
print("\nReshaped 2D Array:")
print(reshaped_2d)
Output:
Reshaped 2D Array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

2. Manipulating 2D Arrays

(a) Shape and Dimensions


[Link] # (rows, cols)
[Link] # 2
[Link] # total elements

(b) Indexing (Accessing Elements)

●​ Row, Column Indexing (zero-based).​

arr[0, 1] # element at row 0, col 1


arr[1, :] # entire row 1
arr[:, 2] # entire column 2

(c) Slicing
arr[0:2, 1:3] # submatrix (rows 0-1, cols 1-2)
(d) Reshaping
[Link](3, 2) # reshape into 3x2

(e) Transpose

●​ Swap rows ↔ columns.

arr.T

(f) Stacking

●​ Combine arrays vertically or horizontally.

a = [Link]([[1, 2], [3, 4]])

b = [Link]([[5, 6], [7, 8]])


[Link]((a, b)) # Vertical stack
[Link]((a, b)) # Horizontal stack
(g) Splitting

●​ Divide array into smaller arrays.

[Link](a, 2) # split into 2 cols

[Link](a, 2) # split into 2 rows

(h) Arithmetic Operations

●​ Element-wise operations are automatic.

arr1 = [Link]([[1, 2], [3, 4]])

arr2 = [Link]([[5, 6], [7, 8]])


print(arr1 + arr2) # element-wise addition
print(arr1 * arr2) # element-wise multiplication

(i) Matrix Operations

●​ Use dot() or @ for matrix multiplication.​

A = [Link]([[1, 2], [3, 4]])


B = [Link]([[5, 6], [7, 8]])
print([Link](B)) # matrix multiplication
print(A @ B) # same as dot()

Indexing in numpy
Indexing in NumPy refers to accessing individual elements or groups of elements
(subarrays) within a NumPy array using their positions (indices). NumPy supports
various forms of indexing, making it highly versatile and efficient.
Indexing Techniques in NumPy:
●​ Basic Indexing: Access single elements using [index] operator.
●​ Negative indexing: Allows to access elements from the end of an array,
rather than the beginning.
●​ Slicing: Access ranges of elements using slicing operator [start:stop:step].
●​ Boolean Indexing: Access elements that meet a specific condition using a
boolean mask.
●​ Fancy Indexing: Access elements using arrays of indices.
●​ Mixed Indexing: Combine different types of indexing for complex
operations.
These techniques allow NumPy arrays to be sliced, filtered, and accessed with
high flexibility, making them powerful for data analysis and manipulation.
Here's a detailed explanation of the different types of indexing in NumPy:
1. Basic Indexing

Indexing means accessing specific elements in a NumPy array.

●​ NumPy uses zero-based indexing (first element = index 0).


●​ Indexing can be done on 1D arrays (vectors) and 2D arrays (matrices).
●​ Numpy allows Forward and Backward Indexing on arrays.

1. Indexing in 1D Arrays using index operator []


A 1D array is like a list.

Example:
import numpy as np
arr = [Link]([10, 20, 30, 40, 50])

(a) Accessing Elements


print(arr[0]) # First element
print(arr[2]) # Third element
print(arr[-1]) # Last element (negative index)
Output:

10
30
50

(b) Slicing (Range of Elements) using slicing operator [::]


Syntax:
newarray= arr[start:stop:step]

print(arr[1:4]) # elements from index 1 to 3


print(arr[:3]) # first 3 elements
print(arr[2:]) # from index 2 to end
print(arr[::2]) # every 2nd element

Output:

[20 30 40]
[10 20 30]
[30 40 50]
[10 30 50]

2. Indexing in 2D Arrays using index operator [r,c]


A 2D array is like a table with rows and columns.

Example:
arr2d = [Link]([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

This is a 3×3 array.

●​ Row index = 0, 1, 2​

●​ Column index = 0, 1, 2

(a) Accessing a Single Element

Syntax: arr[row, column]

print(arr2d[0, 0]) # First row, first column


print(arr2d[1, 2]) # Second row, third column
print(arr2d[-1, -1]) # Last row, last column

Output:

1
6
9

(b) Accessing Rows


print(arr2d[0]) # First row
print(arr2d[1]) # Second row

Output:

[1 2 3]
[4 5 6]

(c) Accessing Columns


print(arr2d[:, 0]) # First column
print(arr2d[:, 1]) # Second column

Output:

[1 4 7]
[2 5 8]

(d) Sub-arrays (Slicing)


print(arr2d[0:2, 1:3]) # First 2 rows, columns 1 and
2
print(arr2d[1:, :2]) # Rows 1 onwards, first 2
columns

Output:

[[2 3]
[5 6]]

[[4 5]
[7 8]]

(e) Step Slicing


print(arr2d[::2, ::2]) # Every 2nd row and column

Output:

[[1 3]
[7 9]]
2. Boolean Indexing
Boolean indexing allows you to access elements based on conditions. This is
especially useful for filtering arrays.
2.1. Boolean Indexing in 1D Arrays
# Boolean array where elements are greater than 25
condition = array_1d > 25
print("Boolean Mask:", condition)
# Use the condition to get elements greater than 25
filtered_array = array_1d[condition]
print("Filtered Array (Elements > 25):", filtered_array)
Output:
Boolean Mask: [False False True True True]
Filtered Array (Elements > 25): [30 40 50]
2.2. Boolean Indexing in 2D Arrays
# Condition: elements greater than 5
condition_2d = array_2d > 5
print("Boolean Mask 2D:\n", condition_2d)
# Use the condition to get elements greater than 5
filtered_2d = array_2d[condition_2d]
print("\nFiltered 2D Array (Elements > 5):", filtered_2d)
Output:
Boolean Mask 2D:
[[False False False]
[False False True]
[ True True True]]
Filtered 2D Array (Elements > 5): [6 7 8 9]
3. Fancy Indexing
Fancy indexing allows you to select specific elements using arrays of indices.
3.1. Fancy Indexing in 1D Arrays
python
Copy code
# Create a list of indices
indices = [0, 2, 4]
# Use the indices to access specific elements
fancy_1d = array_1d[indices]
print("Fancy Indexed 1D Array:", fancy_1d)
Output:
Fancy Indexed 1D Array: [10 30 50]
3.2. Fancy Indexing in 2D Arrays
# Create lists of row and column indices
rows = [0, 1, 2]
columns = [1, 2, 0]
# Use the lists of indices to access specific elements
fancy_2d = array_2d[rows, columns]
print("Fancy Indexed 2D Array:", fancy_2d)
Output:
Fancy Indexed 2D Array: [2 6 7]
4. Mixed Indexing
You can combine different types of indexing (basic, slicing, boolean, fancy) for
complex selections.
Example of Mixed Indexing
# Slice the first two rows, then apply boolean indexing
mixed_indexing = array_2d[0:2, :][array_2d[0:2, :] > 2]
print("Mixed Indexing Result:", mixed_indexing)
Output:
Mixed Indexing Result: [3 4 5 6]

Slicing in numpy
Slicing in NumPy refers to extracting a subset of elements from an array. It allows
for efficient access to specific elements, rows, or columns of an array without
modifying the original array. Slicing is done using the colon (:) operator, and you
can define a range for each axis in a multi-dimensional array.
1. Slicing in 1D Arrays
A 1D NumPy array behaves similarly to a Python list when it comes to slicing. You
can use the basic syntax [start:stop:step] to slice the array.
●​ start: The index at which slicing starts (inclusive).
●​ stop: The index at which slicing stops (exclusive).
●​ step: The number of steps between elements (default is 1).
Example 1.1: Basic Slicing
import numpy as np
# Create a 1D array
array_1d = [Link]([10, 20, 30, 40, 50, 60])
# Slice elements from index 1 to 4 (exclusive)
slice_1d = array_1d[1:4]
print("Sliced 1D Array:", slice_1d)
Output:
Sliced 1D Array: [20 30 40]
Example 1.2: Slicing with Steps
You can specify a step to select every nth element within the slice.
# Slice every second element from index 0 to 5
slice_with_step = array_1d[0:5:2]
print("Sliced 1D Array with Step:", slice_with_step)
Output:
Sliced 1D Array with Step: [10 30 50]
Example 1.3: Omitting start or stop
●​ If start is omitted, it defaults to the beginning of the array.
●​ If stop is omitted, it defaults to the end of the array.
# Slice from the beginning to index 3 (exclusive)
slice_omit_start = array_1d[:3]
print("Sliced Array (Start Omitted):", slice_omit_start)
# Slice from index 2 to the end of the array
slice_omit_stop = array_1d[2:]
print("Sliced Array (Stop Omitted):", slice_omit_stop)
Output:
Sliced Array (Start Omitted): [10 20 30]
Sliced Array (Stop Omitted): [30 40 50 60]
Example 1.4: Negative Indexing in Slicing
You can use negative indices to slice elements from the end of the array.
# Slice the last three elements
slice_negative = array_1d[-3:]
print("Sliced Array with Negative Indices:", slice_negative)
Output:
Sliced Array with Negative Indices: [40 50 60]
2. Slicing in 2D Arrays
In a 2D array, slicing allows you to select specific rows, columns, or subarrays. You
can specify slicing for each dimension separately using [row_start:row_stop,
col_start:col_stop].
Example 2.1: Basic Slicing in 2D Arrays
# Create a 2D array (3 rows, 4 columns)
array_2d = [Link]([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# Slice a subarray: first two rows, first three columns
slice_2d = array_2d[0:2, 0:3]
print("Sliced 2D Array (First Two Rows, First Three Columns):")
print(slice_2d)
Output:
Sliced 2D Array (First Two Rows, First Three Columns):
[[1 2 3]
[5 6 7]]
Example 2.2: Slicing Rows and Columns
You can slice specific rows or columns by omitting the other dimension.
# Slice all rows, and the first two columns
slice_columns = array_2d[:, 0:2]
print("Sliced 2D Array (All Rows, First Two Columns):")
print(slice_columns)
# Slice the first two rows, and all columns
slice_rows = array_2d[0:2, :]
print("Sliced 2D Array (First Two Rows, All Columns):")
print(slice_rows)
Output:
Sliced 2D Array (All Rows, First Two Columns):
[[ 1 2]
[ 5 6]
[ 9 10]]
Sliced 2D Array (First Two Rows, All Columns):
[[1 2 3 4]
[5 6 7 8]]
Example 2.3: Using Negative Indices in 2D Arrays
Negative indices can be used in both row and column slicing to select elements
from the end of the array.
# Slice the last two rows and last two columns
slice_negative_2d = array_2d[-2:, -2:]
print("Sliced 2D Array (Last Two Rows, Last Two Columns):")
print(slice_negative_2d)
Output:
Sliced 2D Array (Last Two Rows, Last Two Columns):
[[ 7 8]
[11 12]]
Example 2.4: Slicing Subarrays
You can extract specific subarrays from a 2D array.
# Extract a 2x2 subarray from the bottom-left corner
subarray = array_2d[1:3, 0:2]
print("Extracted Subarray (2x2 from Bottom-Left Corner):")
print(subarray)
Output:
Extracted Subarray (2x2 from Bottom-Left Corner):
[[ 5 6]
[ 9 10]]
3. Slicing with Steps
You can use the step argument in any dimension to select elements at regular
intervals.
Example 4.1: Slicing with Steps in 1D Arrays
# Slice every second element
step_slice_1d = array_1d[::2]
print("Sliced 1D Array with Steps:", step_slice_1d)
Output:
Sliced 1D Array with Steps: [10 30 50]
Example 4.2: Slicing with Steps in 2D Arrays
# Slice every second row and every second column
step_slice_2d = array_2d[::2, ::2]
print("Sliced 2D Array with Steps (Every Second Row and Column):")
print(step_slice_2d)
Output:
Sliced 2D Array with Steps (Every Second Row and Column):
[[ 1 3]
[ 9 11]]

Iterating in numpy
Iterating over NumPy arrays involves processing elements of the array one by one,
which can be done using loops. NumPy supports efficient iteration over arrays
using Python's for loop. However, the iteration behavior depends on the array’s
dimensions and shape.
●​ 1D arrays: Iteration is straightforward, similar to Python lists.
●​ 2D and higher-dimensional arrays: Single loops iterate over rows; nested
loops or nditer() can be used to iterate over individual elements.
●​ Modifying elements: nditer() with op_flags=['readwrite'] allows in-place
modification.
●​ Indexing during iteration: ndenumerate() allows access to both indices and
values during iteration.
●​ Broadcasting: nditer() can iterate over arrays of different shapes by
broadcasting.
These techniques make it easy to access and manipulate elements efficiently in
NumPy arrays.

1. Iterating over 1D Arrays


Just like a Python list.

import numpy as np
arr = [Link]([10, 20, 30, 40])
for x in arr:
print(x)
Output:

10
20
30
40

2. Iterating over 2D Arrays


●​ Iterating row by row:​

arr2d = [Link]([[1, 2, 3], [4, 5, 6]])


for row in arr2d:
print(row)

Output:

[1 2 3]
[4 5 6]

●​ Iterating element by element (nested loop):​

for row in arr2d:


for element in row:
print(element)

Output:
1
2
3
4
5
6

3. Iterating with nditer()


●​ NumPy provides nditer() to simplify iteration over multi-dimensional
arrays.​

●​ It flattens the array, so you don’t need nested loops.​

arr2d = [Link]([[1, 2, 3], [4, 5, 6]])

for x in [Link](arr2d):
print(x)

Output:

1
2
3
4
5
6

4. Iterating with Index (ndenumerate)


●​ If you also want the index (row, col) while iterating, use ndenumerate().​

arr2d = [Link]([[10, 20], [30, 40]])

for index, value in [Link](arr2d):


print(index, value)

Output:

(0, 0) 10
(0, 1) 20
(1, 0) 30
(1, 1) 40

5. Iterating with Conditions


You can apply conditions while iterating.

arr = [Link]([1, 2, 3, 4, 5])


for x in arr:
if x % 2 == 0:
print(x, "is even")

Output:
2 is even
4 is even

Copying in numpy
When you work with arrays, sometimes you want:

●​ Just a reference (no actual copy).​

●​ A view (shallow copy: shares data, different object).​

●​ A deep copy (fully independent copy).

Copying in NumPy is an important concept that involves creating copies of arrays.


Understanding how copying works is crucial for managing memory efficiently and
ensuring that changes to arrays do not unintentionally affect other arrays. By
choosing the appropriate copying method, you can control memory usage and
ensure that changes to arrays are handled as intended.

Types of Copies in NumPy


1.​ Shallow Copy: A shallow copy creates a new array object but does not
create copies of the data itself. Instead, it references the same data in
memory. Thus, modifications made to the shallow copy will also affect the
original array.
o​ Created using slicing or the view() method.
o​ Share the same data in memory with the original array.
o​ Modifications affect the original array.
2.​ Deep Copy: A deep copy creates a new array object and also creates copies
of the data. This means that modifications made to the deep copy do not
affect the original array.
o​ Created using the copy() method.
o​ Independent of the original array.
o​ Modifications do not affect the original array.

1. Simple Assignment (No Copy)


Syntax:​

b = a

●​ Explanation: b and a point to the same array object in memory.


●​ Changes in one affect the other.​

import numpy as np
a = [Link]([1, 2, 3])
b = a # no copy
b[0] = 99
print("a:", a) # [99 2 3]
print("b:", b) # [99 2 3]

Both changed because they are the same object.

2. View / Shallow Copy (view())


Syntax:​

b = [Link]()

●​ Explanation: Creates a new array object, but it shares the same data.​

●​ If data is modified → both reflect the change.​


●​ If shape is modified → only affects the new array.​

a = [Link]([1, 2, 3])
b = [Link]()
b[0] = 99
print("a:", a) # [99 2 3]
print("b:", b) # [99 2 3]
[Link] = (3, 1)
print("[Link]:", [Link]) # (3,)
print("[Link]:", [Link]) # (3,1)

Data is shared, but shape is independent.

3. Deep Copy (copy())


Syntax:​

b = [Link]()

●​ Explanation: Creates a completely new array with its own data.


●​ Modifying one does not affect the other.

a = [Link]([1, 2, 3])

b = [Link]()
b[0] = 99
print("a:", a) # [1 2 3]
print("b:", b) # [99 2 3]

Independent copies, safe to modify.


4. Slicing (Implicit View)
Syntax:​

b = a[start:end]

●​ Explanation: Slicing creates a view (not a new copy).


●​ Changes affect the original array.​

a = [Link]([10, 20, 30, 40])


b = a[1:3]

b[0] = 99
print("a:", a) # [10 99 30 40]
print("b:", b) # [99 30]

Slicing behaves like view().

5. Using [Link]() Function


Syntax:​

b = [Link](a)
Explanation: Same as [Link](). Produces a deep copy.​

a = [Link]([1, 2, 3])
b = [Link](a)

b[1] = 77
print("a:", a) # [1 2 3]
print("b:", b) # [1 77 3]

Differences Between Copy Types

Method Copies Shares Indepe Example


Data? Data? ndent
Shape?

Assignment No Yes No b=a


(b=a)

Slice (a[1:3]) No Yes No b=a[1:3]

view() No Yes Yes b=[Link]()

copy() / Yes No Yes b=[Link]()


[Link]()

Splitting Arrays in NumPy

Splitting means dividing an array into multiple sub-arrays.​


NumPy provides:

●​ [Link]() → General split (requires exact divisions).​

●​ numpy.array_split() → Allows unequal divisions.​

●​ [Link]() → Horizontal split (for 2D arrays).​

●​ [Link]() → Vertical split (for 2D arrays).​


1. Splitting 1D Arrays

(a) Using split()


Syntax:​

[Link](array, sections)

●​ Splits array into equal-sized parts.​

import numpy as np

arr = [Link]([10, 20, 30, 40, 50, 60])


splits = [Link](arr, 3)

print(splits)

Output:

[array([10, 20]), array([30, 40]), array([50, 60])]

Array is split into 3 equal parts of size 2.

If unequal split is asked, split() will throw an error.

(b) Using array_split()

●​ Allows unequal splits.​

arr = [Link]([10, 20, 30, 40, 50])


splits = np.array_split(arr, 3)

print(splits)
Output:

[array([10, 20]), array([30, 40]), array([50])]

Last split is smaller because the array length isn’t divisible by 3.

2. Splitting 2D Arrays

Example Array:
arr2d = [Link]([[1, 2, 3, 4],
[5, 6, 7, 8]])
print(arr2d)

Output:

[[1 2 3 4]
[5 6 7 8]]

(a) Horizontal Split (hsplit)

●​ Splits columns.​

splits = [Link](arr2d, 2)
print(splits[0])
print(splits[1])

Output:

[[1 2]
[5 6]]
[[3 4]
[7 8]]

Divided into 2 column groups.

(b) Vertical Split (vsplit)

●​ Splits rows.​

splits = [Link](arr2d, 2)
print(splits[0])
print(splits[1])

Output:

[[1 2 3 4]]
[[5 6 7 8]]

Divided into 2 row groups.

(c) Using split() on 2D

●​ You can also use [Link]() along a given axis:​

# Split along columns (axis=1)


print([Link](arr2d, 2, axis=1))

# Split along rows (axis=0)


print([Link](arr2d, 2, axis=0))

Output:
[array([[1, 2],
[5, 6]]), array([[3, 4],
[7, 8]])]

[array([[1, 2, 3, 4]]), array([[5, 6, 7, 8]])]

Function Works Descripti Example


on on

split(arr, n) 1D/2D Equal [Link](arr,3)


splits only

array_split(arr, n) 1D/2D Allows np.array_split(arr


unequal ,3)
splits

hsplit(arr, n) 2D Splits by [Link](arr2d,2)


columns

vsplit(arr, n) 2D Splits by [Link](arr2d,2)


rows

Shape Manipulation in NumPy

1. Shape Basics

●​ Every ndarray has a shape (tuple of dimensions).​

Example:​

import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print([Link]) # (2, 3) → 2 rows, 3 columns
2. Reshape (reshape())

Reshape changes structure but keeps the same data.

(a) 1D Array → Reshape to 2D


arr = [Link](6) # [0 1 2 3 4 5]
reshaped = [Link](2, 3)
print("Original:", arr)
print("Reshaped:\n", reshaped)

Output:

Original: [0 1 2 3 4 5]
Reshaped:
[[0 1 2]
[3 4 5]]

(b) 2D Array → Reshape to 1D or 2D → flattened into 1D.


arr2d = [Link]([[1, 2, 3], [4, 5, 6]])
reshaped = [Link](6,)
print("Original:\n", arr2d)
print("Reshaped:", reshaped)

Output:

Original:
[[1 2 3]
[4 5 6]]
Reshaped: [1 2 3 4 5 6]

(c) Automatic Dimension (-1)


NumPy can infer one dimension automatically.

arr = [Link](12) # 12 elements


reshaped = [Link](3, -1) # -1 means "auto"
print(reshaped)

Output:

[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

NumPy auto-calculated columns = 4.

3. Flattening an Array

●​ flatten() → returns a copy as 1D.​

●​ ravel() → returns a view (linked to original).​

arr2d = [Link]([[1, 2], [3, 4]])


print("Flatten:", [Link]()) # [1 2 3 4]
print("Ravel:", [Link]()) # [1 2 3 4]

4. Transpose (T)

●​ Swaps rows and columns.​

arr2d = [Link]([[1, 2, 3], [4, 5, 6]])


print("Original:\n", arr2d)
print("Transpose:\n", arr2d.T)

Output:

Original:
[[1 2 3]
[4 5 6]]
Transpose:
[[1 4]
[2 5]
[3 6]]

5. Resizing (resize())

●​ Changes the shape permanently (may repeat data if needed).


●​ Unlike reshape, resize modifies the array itself and may repeat
values to fill.

arr = [Link]([1, 2, 3, 4])


[Link]((2, 3))
print(arr)

Output:

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

Summary :

Operation Purpose Example


reshape() Change shape [Link](2,3)
without altering
data

flatten() Flatten to 1D [Link]()


(copy)

ravel() Flatten to 1D [Link]()


(view)

T (transpose) Swap rows & arr.T


columns

resize() Resize array [Link]((2,3))


permanently

Arithmetic Operations in NumPy

NumPy supports element-wise arithmetic operations (on scalars and


arrays of the same shape).

1. Addition-Adds element by element.

Syntax:​

[Link](arr1, arr2) # or arr1 + arr2

Example:​

import numpy as np

arr1 = [Link]([1, 2, 3])


arr2 = [Link]([4, 5, 6])

print(arr1 + arr2)

print([Link](arr1, arr2))

Output:​

[5 7 9]

[5 7 9]

2. Subtraction - Subtracts element by element.

Syntax:​

[Link](arr1, arr2) # or arr1 - arr2

Example:​

print(arr1 - arr2)

print([Link](arr1, arr2))

Output:​

[-3 -3 -3]

[-3 -3 -3]
3. Multiplication -Multiplies each element.

Syntax:​

[Link](arr1, arr2) # or arr1 * arr2

Example:​

print(arr1 * arr2)

print([Link](arr1, arr2))

Output:​

[ 4 10 18]

[ 4 10 18]

4. Division-Divides element by element (returns float).

Syntax:​

[Link](arr1, arr2) # or arr1 / arr2

Example:​

print(arr2 / arr1)

print([Link](arr2, arr1))
Output:​

[4. 2.5 2. ]

[4. 2.5 2. ]

5. Floor Division-Returns integer division results (floored).

Syntax:​

np.floor_divide(arr1, arr2) # or arr1 // arr2

Example:​

print(arr2 // arr1)

print(np.floor_divide(arr2, arr1))

Output:​

[4 2 2]

[4 2 2]

6. Modulus (Remainder)-Computes element-wise remainders.

Syntax:​

[Link](arr1, arr2) # or arr1 % arr2
Example:​

print(arr2 % arr1)

print([Link](arr2, arr1))

Output:​

[0 1 0]

[0 1 0]

7. Power-Exponentiation element by element.

Syntax:​

[Link](arr1, arr2) # or arr1 ** arr2

Example:​

print(arr1 ** 2) # square

print([Link](arr1, arr2)) # arr1^arr2

Output:​

[1 4 9]

[ 1 32 729]

8. Absolute Value
Syntax:​

[Link](arr) # absolute values

Example:​

arr3 = [Link]([-1, -2, 3])

print([Link](arr3))

Output:​

[1 2 3]

9. Reciprocal

Syntax:​

[Link](arr)

Example:​

arr4 = [Link]([1, 2, 4])

print([Link](arr4))

Output:​

[1 0 0]

Since integers are used, results are truncated. With floats:


arr5 = [Link]([1., 2., 4.])

print([Link](arr5))

Output:

[1. 0.5 0.25]

10. Scalar Operations


Arithmetic also works between arrays and [Link] broadcasts the
scalar to all elements.

print(arr1 + 5) # [6 7 8]

print(arr1 * 2) # [2 4 6]

print(arr1 ** 3) # [1 8 27]

Summary

Operation Function O Example Output


p (arr1=[1,2,3],
er arr2=[4,5,6])
at
or
Addition [Link]() + arr1+arr2 [5 7 9]

Subtraction [Link]() - arr1-arr2 [-3 -3


-3]

Multiplication [Link]() * arr1*arr2 [4 10


18]

Division [Link]() / arr2/arr1 [4. 2.5


2.]

Floor np.floor_divide / arr2//arr1 [4 2 2]


Division () /

Modulus [Link]() % arr2%arr1 [0 1 0]

Power [Link]() * arr1**arr2 [1 32


* 729]
Absolute [Link]() – [Link]([-1,-2 [1 2 3]
,3])

Reciprocal [Link]() – [Link] [1. 0.5


([1.,2.,4.]) 0.25]

Operations on 2D Arrays- Matrix Operations in NumPy

A matrix is simply a 2D NumPy array. NumPy provides many built-in


functions for matrix arithmetic and linear algebra.

1. Matrix Creation
import numpy as np

A = [Link]([[1, 2],
[3, 4]])

B = [Link]([[5, 6],
[7, 8]])
print("Matrix A:\n", A)
print("Matrix B:\n", B)

2. Element-wise Operations
These are applied element by element (not true matrix multiplication).

print(A + B) # Addition
print(A - B) # Subtraction
print(A * B) # Element-wise multiplication
print(A / B) # Element-wise division

Output:

[[ 6 8]
[10 12]]

[[-4 -4]
[-4 -4]]

[[ 5 12]
[21 32]]

[[0.2 0.33333333]
[0.42857143 0.5 ]]

3. Matrix Multiplication
True matrix multiplication = dot product.

Method 1: [Link]()
print([Link](A, B))

Method 2: @ operator
print(A @ B)

Output:

[[19 22]
[43 50]]
4. Transpose
Swaps rows and columns.

print(A.T)

Output:

[[1 3]
[2 4]]

5. Determinant
print([Link](A))

Output:

-2.0000000000000004

The determinant of A is -2.

6. Inverse
print([Link](A))

Output:

[[-2. 1. ]
[ 1.5 -0.5]]

Inverse exists only if determinant ≠ 0.

7. Rank of a Matrix
print([Link].matrix_rank(A))
Output:

8. Trace
(Sum of diagonal elements).

print([Link](A)) # 1 + 4 = 5

9. Norms
Length (magnitude) of a matrix.

print([Link](A))

Output:

5.477225575051661

10. Eigenvalues and Eigenvectors


values, vectors = [Link](A)
print("Eigenvalues:", values)
print("Eigenvectors:\n", vectors)

Output (approx):

Eigenvalues: [-0.37228132 5.37228132]


Eigenvectors:
[[-0.82456484 -0.41597356]
[ 0.56576746 -0.90937671]]

Aggregate Functions in NumPy

Aggregate functions are operations that summarize data in an array (like


sum, mean, min, max). They can work on the whole array or along a
specific axis.

1. Sum
Syntax:​

[Link](arr, axis=None)

Example:​

import numpy as np
arr = [Link]([[1, 2, 3],
[4, 5, 6]])

print([Link](arr)) # Total sum


print([Link](arr, axis=0)) # Column-wise sum
print([Link](arr, axis=1)) # Row-wise sum
Output:​

21
[5 7 9]
[ 6 15]

2. Min & Max


Syntax:​

[Link](arr, axis=None)
[Link](arr, axis=None)
Example:​

print([Link](arr)) # Minimum
print([Link](arr)) # Maximum
print([Link](arr, axis=0)) # Column min
print([Link](arr, axis=1)) # Row max
Output:​

1
6
[1 2 3]
[3 6]

3. Mean (Average)
Syntax:​

[Link](arr, axis=None)

Example:​

print([Link](arr)) # Mean of all
print([Link](arr, axis=0)) # Column mean
print([Link](arr, axis=1)) # Row mean
Output:​

3.5
[2.5 3.5 4.5]
[2. 5.]
4. Median
Syntax:​

[Link](arr, axis=None)
Example:​

print([Link](arr)) # Median of all
print([Link](arr, axis=0))# Column median
Output:​

3.5
[2.5 3.5 4.5]

5. Standard Deviation & Variance


Syntax:​

[Link](arr, axis=None) # Standard deviation
[Link](arr, axis=None) # Variance
Example:​

print([Link](arr)) # Std dev
print([Link](arr)) # Variance
Output:​

1.707825127659933
2.9166666666666665

6. Argmin & Argmax (Index of Min/Max)-Returns flattened


index by default.
Syntax:​

[Link](arr, axis=None)
[Link](arr, axis=None)
Example:​

print([Link](arr)) # Index of min
print([Link](arr)) # Index of max
Output:​

0
5

7. Cumulative Sum & Product


Syntax:​

[Link](arr, axis=None)
[Link](arr, axis=None)
Example:​

print([Link](arr)) # Running total
print([Link](arr)) # Running product
Output:​

[ 1 3 6 10 15 21]
[ 1 2 6 24 120 720]

Summary
Function Description Example
[Link] Sum of [Link](arr)
elements

[Link] Minimum value [Link](arr, axis=0)

[Link] Maximum value [Link](arr, axis=1)

[Link] Average [Link](arr)

[Link] Middle value [Link](arr)

[Link] Standard [Link](arr)


deviation

[Link] Variance [Link](arr)

[Link] Index of min [Link](arr)

[Link] Index of max [Link](arr)

[Link] Cumulative sum [Link](arr)

[Link] Cumulative [Link](arr)


product

Operations on NumPy Arrays

Creation Operations
Create arrays in different ways:

import numpy as np
[Link]([1,2,3]) # From list
[Link]((2,3)) # Array of zeros
[Link]((2,3)) # Array of ones
[Link]((2,3)) # Empty (garbage
values)
[Link](0,10,2) # Range
[Link](0,1,5) # Evenly spaced
values
[Link](1,10,(2,3)) # Random integers

2. Inspection Operations
Check properties of arrays:

arr = [Link]([[1,2,3],[4,5,6]])
print([Link]) # (2,3) → 2 rows, 3 cols
print([Link]) # 2 → dimensions
print([Link]) # 6 → total elements
print([Link]) # int64 → type
print([Link]) # 8 → bytes per element
print([Link]) # 48 → total memory

3. Indexing and Slicing


1D:
arr = [Link]([10,20,30,40,50])
print(arr[0]) # 10
print(arr[-1]) # 50
print(arr[1:4]) # [20 30 40]
2D:
arr2d = [Link]([[1,2,3],[4,5,6],[7,8,9]])
print(arr2d[1,2]) # 6
print(arr2d[:,1]) # [2 5 8] (2nd col)
print(arr2d[0:2,1:3]) # [[2 3],[5 6]]

4. Iteration
for row in arr2d:
print(row)

for x in [Link](arr2d):
print(x)

for idx, val in [Link](arr2d):


print(idx, val)

5. Shape Manipulation
arr = [Link](6) # [0 1 2 3 4 5]
print([Link](2,3)) # Change shape
print([Link]()) # Flatten to 1D
print(arr.T) # Transpose
print(arr[:, [Link]]) # Add new axis (column
vector)

6. Copying
a = [Link]([1,2,3])
b = a # Assignment (no copy)
c = [Link]() # View (shallow copy)
d = [Link]() # Deep copy

7. Arithmetic Operations
Element-wise:

x = [Link]([1,2,3])
y = [Link]([4,5,6])

print(x + y) # [5 7 9]
print(x - y) # [-3 -3 -3]
print(x * y) # [ 4 10 18]
print(x / y) # [0.25 0.4 0.5]
print(x ** 2) # [1 4 9]

With scalars:

print(x + 5) # [6 7 8]
print(x * 2) # [2 4 6]

8. Comparison Operations
print(x > 2) # [False False True]
print(x == 2) # [False True False]
print([Link](x > 0)) # True
print([Link](x > 2)) # True

9. Logical Operations
a = [Link]([True, False, True])
b = [Link]([False, False, True])

print(np.logical_and(a, b)) # [False False True]


print(np.logical_or(a, b)) # [ True False True]
print(np.logical_not(a)) # [False True False]

10. Aggregate Functions


arr = [Link]([[1,2,3],[4,5,6]])
print([Link]()) # 21
print([Link]()) # 1
print([Link]()) # 6
print([Link]()) # 3.5
print([Link]()) # 1.707...
print([Link](axis=0)) # [5 7 9] (column sum)
print([Link](axis=1)) # [ 6 15] (row sum)

11. Linear Algebra Operations


A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])

print([Link](A,B)) # Matrix multiplication


print([Link](A)) # Inverse
print([Link](A)) # Determinant
print([Link](A)) # Eigenvalues, eigenvectors

Comparison: Python List vs Array Module vs NumPy ndarray


Python language also has an array data structure, but it is not as versatile, efficient and useful
as the NumPy array.
Feature / Python List array (std module) NumPy ndarray
Aspect

Definition Built-in dynamic Homogeneous array Powerful N-dimensional


sequence in with fixed typecode homogeneous array
Python

Data Type Can store mixed Must store same type Must store same type
types (int, str, (defined by typecode) (dtype)
float, etc.)

Memory Usage High (stores Low (compact C-style Lowest & efficient
references + memory) (contiguous block in C)
objects)

Speed Slower (dynamic Faster than list (typed Fastest (vectorized ops in
typing overhead) data) C)

Size flexibility Dynamic, can Dynamic, but elements Fixed dtype, resizing costly
grow/shrink must match typecode

Mathematical Requires loops / Basic (no math Rich support (+ - * /,


Operations manual functions) dot, linear algebra)
implementation

Dimensionality 1D only (nested 1D only Supports 1D, 2D, nD


lists for 2D, but (tensors)
messy)

Libraries Built-in, always Built-in, always Requires installing NumPy


available available

Use cases General purpose, Memory-efficient typed Scientific computing,


small data, mixed arrays (e.g., bytes, AI/ML, Data Science,
data ints, floats) large-scale numerical work

Example [1, "a", 3.5] [Link]('i',[ [Link]([[1,2,3],[4


1,2,3]) ,5,6]])

You might also like