0% found this document useful (0 votes)
3 views

Num Py

Aaaa

Uploaded by

Harib Khan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Num Py

Aaaa

Uploaded by

Harib Khan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Introduction to NumPy

1.1 What is NumPy?

NumPy, short for Numerical Python, is an open-source Python library used for working with
arrays and performing numerical operations. It allows for efficient operations on large datasets
and offers a wide range of mathematical functions.

1.2 Importance of NumPy in Data Science

NumPy is critical in data science for several reasons:

1. Efficient Computations: NumPy arrays are more efficient than Python lists because they
use less memory and provide better performance for mathematical operations.
2. Support for Multidimensional Arrays: You can easily create and manipulate arrays of
any dimension (1D, 2D, 3D, etc.), which is essential for handling datasets.
3. Integration with Other Libraries: Many data science libraries, such as Pandas,
TensorFlow, and Scikit-learn, rely on NumPy arrays.

1.3 NumPy Arrays

NumPy arrays are the core data structure of the NumPy library, designed for efficient storage and
manipulation of large datasets.

1.3.1 Creating Arrays

You can create NumPy arrays using the numpy.array() function, which converts lists or tuples
into arrays.

Creating Arrays (1D, 2D, and nD arrays)

NumPy arrays can be created in various dimensions:

 1D array: A simple linear array.


 2D array: A matrix-like structure.
 nD array: Arrays with n dimensions.

1.3.1.1 1D Arrays

A 1D array is a one-dimensional array that holds a sequence of elements.

Example Code:
import numpy as np
# Creating a 1D array
array_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:", array_1d)

Output:
1D Array: [1 2 3 4 5]

1.3.1.2 2D Arrays

A 2D array is a two-dimensional array that holds data in a grid format, similar to a matrix.

Example Code:
# Creating a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:\n", array_2d)

Output:
2D Array:
[[1 2 3]
[4 5 6]]

1.3.1.3 nD Arrays

nD arrays are generalizations of 1D and 2D arrays to higher dimensions, allowing for complex
data structures.

Example Code:
# Creating a 3D array
array_nd = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("nD Array:\n", array_nd)

Output:
nD Array:
[[[1 2]
[3 4]]

[[5 6]
[7 8]]]

1.4 Array Attributes

NumPy arrays come with several built-in attributes that provide useful information about their
structure and data. Understanding these attributes is crucial for effectively working with arrays in
numerical computing.

1.4.1 shape
The shape attribute returns a tuple representing the dimensions of the array. Each element in the
tuple corresponds to the size of the array along a particular axis.

Example Code:
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape of the array:", array_2d.shape)

Output:
Shape of the array: (2, 3)

1.4.2 size

The size attribute returns the total number of elements in the array, which is the product of the
sizes of all dimensions.

Example Code:
print("Total number of elements:", array_2d.size)

Output:
Total number of elements: 6

1.4.3 dtype

The dtype attribute indicates the data type of the elements in the array, which helps to understand
how the data is stored and manipulated.

Example Code:
print("Data type of the array:", array_2d.dtype)

Output:
Data type of the array: int64

1.4.4 nbytes

The nbytes attribute returns the total number of bytes used by the array's data. This is calculated
as the product of the size of the array and the size of each element.

Example Code:
print("Total bytes consumed by the array:", array_2d.nbytes)

Output:
Total bytes consumed by the array: 48

1.4.5 ndim
The ndim attribute returns the number of dimensions (axes) of the array. This is useful for
understanding the structure of the array.

Example Code:
print("Number of dimensions:", array_2d.ndim)

Output:
Number of dimensions: 2

1.5.6 flat

The flat attribute returns an iterator that can be used to access the elements of the array in a
flattened (1D) form.

Example Code:
print("Flattened array elements:", list(array_2d.flat))

Output:
Flattened array elements: [1, 2, 3, 4, 5, 6]

1.6 Array Creation Functions

NumPy provides several array creation functions that allow users to generate arrays of various
shapes, sizes, and data types efficiently. These functions are essential for initializing arrays
before performing computations or manipulations.

1.6.1 zeros

The zeros function creates an array filled with zeros. You can specify the shape of the array as an
argument.

Example Code:
import numpy as np

# Creating a 2D array of zeros


array_zeros = np.zeros((2, 3))
print("Array of zeros:\n", array_zeros)

Output:
Array of zeros:
[[0. 0. 0.]
[0. 0. 0.]]

In this case, NumPy shows 0. instead of 0 to reflect the floating-point precision of the array
elements. The . signifies that the values are 0.0 in floating-point format. Even though the values
are zeros, the data type float requires the dot.
If you want integers instead of floats, you can specify the data type explicitly using dtype=int

array_zeros_int = np.zeros((2, 3), dtype=int)

print("Array of zeros:\n", array_zeros_int)

1.6.2 empty

The empty function creates an array without initializing its values, meaning it can contain
arbitrary data. This is useful for creating an array that will be filled later.

Example Code:
# Creating an empty array
array_empty = np.empty((2, 3))
print("Empty array:\n", array_empty)

Output:
Empty array:
[[0. 0. 0.]
[0. 0. 0.]]

(Note: The output may contain arbitrary values.)

1.6.3 identity

The identity function creates an identity matrix of a specified size. An identity matrix is a square
matrix with ones on the diagonal and zeros elsewhere.

Example Code:
# Creating a 3x3 identity matrix
array_identity = np.identity(3)
print("Identity matrix:\n", array_identity)

Output:
Identity matrix:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

1.6.4 range

The range function is not directly a NumPy function, but NumPy provides a similar function
called np.arange(), which generates evenly spaced values within a specified range.

Example Code:
# Creating an array of evenly spaced values
array_range = np.arange(0, 10, 2)
print("Array with range:\n", array_range)

Output:
Array with range:
[0 2 4 6 8]

1.6.5 linspace

The linspace function generates an array of evenly spaced values over a specified interval. You
can define the start and end values, along with the number of samples.

Example Code:
# Creating an array of 5 evenly spaced values between 0 and 1
array_linspace = np.linspace(0, 1, 5)
print("Linspace array:\n", array_linspace)

Output:
Linspace array:
[0. 0.25 0.5 0.75 1. ]

1.6.6 reshape

The reshape function changes the shape of an existing array without changing its data. You can
specify the new shape as an argument.

Example Code:
# Reshaping an array
array_reshape = np.arange(6).reshape(2, 3)
print("Reshaped array:\n", array_reshape)

Output:
Reshaped array:
[[0 1 2]
[3 4 5]]

np.arange(6): This creates a 1D NumPy array with values ranging from 0 to 5, i.e., [0, 1, 2, 3, 4,
5].
.reshape(2, 3): This reshapes the 1D array into a 2D array with 2 rows and 3 columns.

1.6.7 ravel

The ravel function flattens an n-dimensional array into a 1D array. It returns a contiguous
flattened array.

Example Code:
# Creating a 2D array and flattening it
array_ravel = array_reshape.ravel()
print("Flattened array:\n", array_ravel)

Output:
Flattened array:
[0 1 2 3 4 5]

1.7 Array Indexing and Slicing

Array indexing and slicing in NumPy allow you to access and manipulate specific elements or
subsets of data within an array. This functionality is essential for data analysis and scientific
computing, enabling efficient data retrieval and modification.

1.7.1 np.array(x)

The np.array(x) function is used to create a NumPy array from an existing list, tuple, or other
array-like structure. Once the array is created, you can index or slice it to retrieve specific
elements or subsets.

Example Code:
import numpy as np

# Creating a NumPy array from a list


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

# Indexing the first element


first_element = array_x[0]

# Slicing the first three elements


slice_elements = array_x[:3]

print("Original array:", array_x)


print("First element:", first_element)
print("Slice of first three elements:", slice_elements)

Output:
Original array: [1 2 3 4 5]
First element: 1
Slice of first three elements: [1 2 3]

1.7.2 T(T1ranspose)
The T attribute returns the transpose of an array. Transposing an array switches its rows and
columns, which is particularly useful in linear algebra and data manipulation.

Example Code:
# Creating a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])

# Transposing the array


transposed_array = array_2d.T

print("Original 2D array:\n", array_2d)


print("Transposed array:\n", transposed_array)

Output:
Original 2D array:
[[1 2 3]
[4 5 6]]
Transposed array:
[[1 4]
[2 5]
[3 6]]

1.8 Array Operations

NumPy provides a variety of array operations that allow you to perform computations and
manipulations on arrays efficiently. These operations include statistical functions, logical
operations, and methods for obtaining indices of elements based on specific criteria.

1.8.1 sum

The sum() function calculates the sum of all elements in the array. You can also specify an axis
to sum along.

Example Code:
array_sum = np.array([[1, 2, 3], [4, 5, 6]])
total_sum = array_sum.sum()
print("Total sum of array elements:", total_sum)

Output:
Total sum of array elements: 21

1.8.2 max

The max() function returns the maximum value in the array.

Example Code:
max_value = array_sum.max()
print("Maximum value in the array:", max_value)

Output:
Maximum value in the array: 6

1.8.3 min

The min() function returns the minimum value in the array.

Example Code:
min_value = array_sum.min()
print("Minimum value in the array:", min_value)

Output:
Minimum value in the array: 1

1.8.4 count_nonzero(ary)

The count_nonzero() function counts the number of non-zero elements in the array.

Example Code:
nonzero_count = np.count_nonzero(array_sum)
print("Count of non-zero elements:", nonzero_count)

Output:
Count of non-zero elements: 6

1.8.5 nonzero(ary)

The nonzero() function returns the indices of the non-zero elements in the array.

Example Code:
nonzero_indices = np.nonzero(array_sum)
print("Indices of non-zero elements:", nonzero_indices)

Output:
Indices of non-zero elements: (array([0, 0, 0, 1, 1, 1]), array([0, 1, 2, 0, 1, 2]))

1.8.6 where(ar > 5)

The where() function returns the indices of elements that meet a specified condition.

Example Code:
condition_indices = np.where(array_sum > 5)
print("Indices where elements are greater than 5:", condition_indices)
Output:
Indices where elements are greater than 5: (array([1]), array([2]))
NOTE: First array represents the row indices and the second array represents the column indices.
The element 6 is located at row 1 (the second row) and column 2 (the third column) in the 2D
array

1.8.7 argmax

The argmax() function returns the index of the maximum value in the array.

Example Code:
max_index = array_sum.argmax()
print("Index of the maximum value:", max_index)

Output:
Index of the maximum value: 5
NOTE: The maximum value is 6, and its index in this flattened version is 5

1.8.8 argmin

The argmin() function returns the index of the minimum value in the array.

Example Code:
min_index = array_sum.argmin()
print("Index of the minimum value:", min_index)

Output:
Index of the minimum value: 0

1.8.9 argsort

The argsort() function returns the indices that would sort the array.

Example Code:
sorted_indices = array_sum.argsort()
print("Indices that would sort the array:", sorted_indices)

Output:
Indices that would sort the array: [0 1 2 3 4 5]

1.8.10 sum(axis=0)

The sum(axis=0) function computes the sum along the specified axis (0 refers to rows).

Example Code:
sum_axis_0 = array_sum.sum(axis=0)
print("Sum along axis 0:", sum_axis_0)

Output:
Sum along axis 0: [5 7 9]
Explain:
When summing along axis 0 (column-wise):

Column 1: 1 + 4 = 5
Column 2: 2 + 5 = 7
Column 3: 3 + 6 = 9
So, the result is [5, 7, 9]

1.8.11 sum(axis=1)

The sum(axis=1) function computes the sum along the specified axis (1 refers to columns).

Example Code:
sum_axis_1 = array_sum.sum(axis=1)
print("Sum along axis 1:", sum_axis_1)

Output:
Sum along axis 1: [ 6 15]

1.8.12 argmax(axis=0)

The argmax(axis=0) function returns the indices of the maximum values along the specified axis
(0 refers to rows).

Example Code:
max_index_axis_0 = array_sum.argmax(axis=0)
print("Indices of max values along axis 0:", max_index_axis_0)

Output:
Indices of max values along axis 0: [1 1 1]
Explain :
When checking for the maximum values along axis 0 (column-wise):

Column 1: max(1, 4) → 4 (index 1)


Column 2: max(2, 5) → 5 (index 1)
Column 3: max(3, 6) → 6 (index 1)
So, the result is [1, 1, 1], meaning that in each column, the maximum value is located in row 1
(the second row)

1.8.13 argmax(axis=1)
The argmax(axis=1) function returns the indices of the maximum values along the specified axis
(1 refers to columns).

Example Code:
max_index_axis_1 = array_sum.argmax(axis=1)
print("Indices of max values along axis 1:", max_index_axis_1)

Output:
Indices of max values along axis 1: [2 2]

1.8.14 argsort(axis=0)

The argsort(axis=0) function returns the indices that would sort the array along the specified axis
(0 refers to rows).

Example Code:
sorted_indices_axis_0 = array_sum.argsort(axis=0)
print("Indices that would sort the array along axis 0:", sorted_indices_axis_0)

Output:
Indices that would sort the array along axis 0: [[0 0 0]
[1 1 1]]
Explain : This indicates that the first row remains at index 0 for all columns (as it contains the
smaller values), and the second row at index 1 contains the larger values.

1.8.15 argsort(axis=1)

The .argsort(axis=1) function returns the indices that would sort the array along the specified
axis (1 refers to columns).

Example Code:
sorted_indices_axis_1 = array_sum.argsort(axis=1)
print("Indices that would sort the array along axis 1:", sorted_indices_axis_1)

Output:
Indices that would sort the array along axis 1: [[0 1 2]
[0 1 2]]

1.9 Array Arithmetic

NumPy allows for efficient arithmetic operations on arrays. These operations can be performed
element-wise, enabling powerful mathematical computations and data manipulations in a
straightforward manner.

1.9.1 array1 + array2


You can use the + operator to add two arrays element-wise. If the arrays are of the same shape,
each element in the first array is added to the corresponding element in the second array.

Example Code:
import numpy as np

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


array2 = np.array([4, 5, 6])
sum_array = array1 + array2

print("Result of array1 + array2:", sum_array)

Output:
Result of array1 + array2: [5 7 9]

1.9.2 array1 * array2

Similarly, you can use the * operator to multiply two arrays element-wise. Each element in the
first array is multiplied by the corresponding element in the second array.

Example Code:
product_array = array1 * array2

print("Result of array1 * array2:", product_array)

Output:
Result of array1 * array2: [ 4 10 18]

1.9.3 np.sqrt(array)

The np.sqrt() function computes the square root of each element in the array. This operation is
also performed element-wise.

Example Code:
sqrt_array = np.sqrt(array1)

print("Square root of array1:", sqrt_array)

Output:
Square root of array1: [1. 1.41421356 1.73205081]

You might also like