0% found this document useful (0 votes)
28 views30 pages

Numpy - Data Science

Numpy, or Numerical Python, is a library that provides functions for linear algebra, Fourier transforms, and matrix operations, utilizing n-dimensional arrays for faster performance than Python lists. It includes functionalities for creating, manipulating, and performing mathematical operations on arrays and matrices, as well as generating numerical ranges. The document also demonstrates basic usage of Numpy for linear algebra and Fourier transforms through example code snippets.

Uploaded by

Shivam Jha
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)
28 views30 pages

Numpy - Data Science

Numpy, or Numerical Python, is a library that provides functions for linear algebra, Fourier transforms, and matrix operations, utilizing n-dimensional arrays for faster performance than Python lists. It includes functionalities for creating, manipulating, and performing mathematical operations on arrays and matrices, as well as generating numerical ranges. The document also demonstrates basic usage of Numpy for linear algebra and Fourier transforms through example code snippets.

Uploaded by

Shivam Jha
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
You are on page 1/ 30

Numpy

- Numpy stands for numerical python


- it provides a lot of functions to work in a Domain of Liner Algebra,
Fourier Transform and Matrices
- it provides a Functions Related to the Arrays
- Numpy Creates an Array called nD-Array(N Dimentional)
- the working of nD-array is Faster than List in Python
- Most of the Part of Numpy Library is Created by using C & C++ and some
part of is Python

In [1]: import numpy as np

In [2]: print(np.__version__)
1.24.3

Linear algebra
- Linear algebra deals with vector spaces and linear mappings between
these spaces. Here's a simple program that
demonstrates basic linear algebra operations using NumPy

In [3]: import numpy as np


# Define two matrices
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

print(f"A = \n{A}")
print(f"B = \n{B}")
# Matrix addition
C = A + B
print("\nMatrix Addition:")
print(C)

# Matrix multiplication
D = np.dot(A, B)
print("\nMatrix Multiplication:")
print(D)

# Matrix transpose
A_transpose = np.transpose(A)
print("\nMatrix Transpose:")
print(A_transpose)

# Matrix determinant
det_A = np.linalg.det(A)
print("\nDeterminant of A:", det_A)
A =
[[1 2]
[3 4]]
B =
[[5 6]
[7 8]]

Matrix Addition:
[[ 6 8]
[10 12]]

Matrix Multiplication:
[[19 22]
[43 50]]

Matrix Transpose:
[[1 3]
[2 4]]

Determinant of A: -2.0000000000000004

Fourier Transform:
- The Fourier Transform is a mathematical technique used to decompose a
function into its constituent frequencies.
Here's a simple program that computes and plots the Fourier Transform
of a signal using NumPy

In [4]: import matplotlib.pyplot as plt


# Generate a signal (sine wave)
fs = 1000 # Sampling frequency
t = np.linspace(0, 1, fs, endpoint=False)
signal = np.sin(2 * np.pi * 5 * t) + np.sin(2 * np.pi * 10 * t)

# Compute the Fourier Transform


dft = np.fft.fft(signal)
freq = np.fft.fftfreq(len(signal), 1/fs)

# Plot the signal and its Fourier Transform


plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.plot(t, signal)
plt.title('Original Signal')
plt.xlabel('Time')
plt.ylabel('Amplitude')

plt.subplot(2, 1, 2)
plt.plot(freq, np.abs(dft))
plt.title('Fourier Transform')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.xlim(0, 20) # Limit the x-axis to show frequencies up to 20 Hz
plt.tight_layout()
plt.show()
In the Above program:
- We generate a signal composed of two sine waves with frequencies 5 Hz
and 10 Hz.
- We compute the Fourier Transform of the signal using np.fft.fft().
- We plot the original signal and its Fourier Transform.

Matrices:
- Matrices are rectangular arrays of numbers arranged in rows and
columns. Here's a simple program that demonstrates
basic matrix operations using NumPy:

In [5]: # Define a matrix


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

# Matrix addition
result_add = matrix + 10
print("Matrix Addition (Scalar):")
print(result_add)

# Element-wise multiplication
result_mul = matrix * 2
print("\nElement-wise Multiplication (Scalar):")
print(result_mul)

# Matrix multiplication (Dot product)


identity_matrix = np.eye(3)
result_dot = np.dot(matrix, identity_matrix)
print("\nMatrix Multiplication (Dot product):")
print(result_dot)

# Matrix transpose
matrix_transpose = np.transpose(matrix)
print("\nMatrix Transpose:")
print(matrix_transpose)
Matrix Addition (Scalar):
[[11 12 13]
[14 15 16]
[17 18 19]]

Element-wise Multiplication (Scalar):


[[ 2 4 6]
[ 8 10 12]
[14 16 18]]

Matrix Multiplication (Dot product):


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

Matrix Transpose:
[[1 4 7]
[2 5 8]
[3 6 9]]

Array
- An array in NumPy is represented as an n-dimensional array (nd-array).
- In NumPy, the array function is used to create arrays, and it needs to
be called with the NumPy library whenever
required.
- To create an n-dimensional array, we use the array() function. This
function takes a list or tuple as a parameter.
- An array is a collection of items.
- The idea is to store multiple items of the same type together (so its
work faster than list)

Creating a Array
- Array in Python can be created by importing array module.

syntax:
- array(data_type,value_list)

In [6]: # importing 'array' for the array creations


import array as arr

# array with int datatype


# Create an array of signed integers (typecode 'i')
num = arr.array('i',[2,1,3])
print(num)
print(type(num))
array('i', [2, 1, 3])
<class 'array.array'>

In [7]: ### Array Indexing


num[2]

Out[7]: 3

In [8]: ### Array Slicing


num[1:3]
Out[8]: array('i', [1, 3])

In [9]: import array as arr


# now will try to create multi dimentional array
num1 = arr.array('i',[[1,23,5],[9,2,32]]) # If you want to create multidimentional

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[9], line 3
1 import array as arr
2 # now will try to create multi dimentional array
----> 3 num1 = arr.array('i',[[1,23,5],[9,2,32]])

TypeError: 'list' object cannot be interpreted as an integer

Note: If you want to create multidimentional array you want to use numpy library¶
In [10]: import numpy as np
num1 = np.array([[1, 23, 5], [9, 2, 32]])
num1

Out[10]: array([[ 1, 23, 5],


[ 9, 2, 32]])

In [11]: ## Creating 0-d, 1-d, 2-d and 3-d Array


# o-d
zero_a=np.array(23)
print(zero_a)
print(f"type= {type(zero_a)}")
print(f"{zero_a.ndim} Dimention Array")
# 1-d
a=np.array([1,2,3]) # array of 0-d elements
print("\n",a)
print(f"type= {type(a)}")
print(f"{a.ndim} Dimention Array")
# 2-d # 2-d means we have to pass 2 sub list
a=np.array([[1,2,3],[4,5,6]]) # array of 1-d arrays
print("\n",a)
print(f"type= {type(a)}")
print(f"{a.ndim} Dimention Array")
# 3-d
a=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[0,1,2]]]) # array of 2-d arrays
print("\n",a)
print(f"type= {type(a)}")
print(f"{a.ndim} Dimention Array")
23
type= <class 'numpy.ndarray'>
0 Dimention Array

[1 2 3]
type= <class 'numpy.ndarray'>
1 Dimention Array

[[1 2 3]
[4 5 6]]
type= <class 'numpy.ndarray'>
2 Dimention Array

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

[[7 8 9]
[0 1 2]]]
type= <class 'numpy.ndarray'>
3 Dimention Array

Converting Arrays with Existing Data


- numpy.asarray()
- numpy.frombuffer()
- numpy.fromiter()

In [12]: # 1) numpy.asarray()
#-------------------
# The numpy.asarray() function converts input to an array. If the input is already an nd
# Otherwise, it creates a new array. This function is particularly useful when you want
# into a NumPy array.

# Syntax: numpy.asarray(a, dtype=None, order=None)


# a : Input data, which can be a list, tuple, or another array-like object.
# dtype : Data-type of the output array. If not provided, the data type of the input is
# order : Specifies the memory layout of the array. By default, it's set to 'C' (row-maj

#Example:
# Convert a list to a NumPy array
my_list = [1, 2, 3, 4, 5]
np_array = np.asarray(my_list)

print(np_array)
[1 2 3 4 5]

In [13]: # 2. numpy.frombuffer()
# ----------------------
# The numpy.frombuffer() function interprets a buffer as a one-dimensional array. This f
# stored in a buffer-like object (e.g., bytes object) and you want to create a NumPy arr

# Syntax: numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)


# buffer: Input buffer object.
# dtype: Data-type of the output array. Default is float.
# count: Number of items to read. Default is -1, which reads all data from the buffer.
# offset: Starting position to read from the buffer. Default is 0.

# Example:

# Create a bytes object (buffer)


buffer = b'Hello World!'
# Convert the buffer to a NumPy array of integers
np_array = np.frombuffer(buffer, dtype='S1')

print(np_array)
[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd' b'!']

In [14]: # 3. numpy.fromiter()
# The numpy.fromiter() function creates a new one-dimensional array from an iterable obj
# This function is useful when you have an iterable object (e.g., Python range) and you

# Syntax: numpy.fromiter(iterable, dtype, count=-1)


# iterable: Input iterable object.
# dtype: Data-type of the output array.
#count: Number of items to read. Default is -1, which reads all items from the iterable.

# Example:
# Create a Python range object
my_range = range(10)

# Convert the range to a NumPy array


np_array = np.fromiter(my_range, dtype=int)

print(np_array)
[0 1 2 3 4 5 6 7 8 9]

arrays with numerical ranges


- Arrays with numerical ranges in NumPy are arrays created with a
sequence of numerical values that follow a specific
range pattern. NumPy provides several functions to generate arrays
with numerical ranges efficiently. These arrays
can be created with specified start, stop, and step values, allowing
for easy generation of evenly spaced sequences
of numbers.

- Here are some functions in NumPy used for creating arrays with
numerical ranges:
- numpy.arange()
- numpy.linspace()
- numpy.logspace()

In [15]: # 1) numpy.arange(): This function creates an array with evenly spaced values within a sp

# Syntax: numpy.arange(start, stop, step, dtype)

# Create an array from 0 to 9 with step 1


arr1 = np.arange(10)
print(arr1)

# Create an array from 1 to 10 with step 2


arr2 = np.arange(1, 11, 2,dtype='float')
print(arr2)
[0 1 2 3 4 5 6 7 8 9]
[1. 3. 5. 7. 9.]

In [16]: # 2) numpy.linspace(): This function creates an array with evenly spaced values over a sp
# Syntax : numpy.linspace(start, stop, num=50, endpoint=True, dtype)

# Create an array of 10 equally spaced values from 0 to 1


arr1 = np.linspace(0, 1, num=10,dtype='float',retstep=True) # default dtype='float' #
print(arr1)

# Create an array of 5 equally spaced values from 1 to 2 (inclusive)


arr2 = np.linspace(1, 2, num=5, endpoint=False,retstep=True)
print(arr2)
(array([0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ]), 0.1111111111111111)
(array([1. , 1.2, 1.4, 1.6, 1.8]), 0.2)

In [17]: # 3) numpy.logspace(): This function creates an array with evenly spaced values on a log

# Syntax: numpy.logspace(start, stop, num=50, base=10.0, endpoint=True)


import numpy as np

# Create an array of 5 logarithmically spaced values from 10^1 to 10^2


arr = np.logspace(1, 2, num=5) # default='float'
print(arr)
[ 10. 17.7827941 31.6227766 56.23413252 100. ]

Shape() and Reshape()


- In NumPy, the shape attribute of an array returns the dimensions
(shape) of the array. It is a tuple indicating
the size of each dimension of the array. The reshape() function allows
you to change the shape of an array without
changing its data.

In [18]: # Create a 2D array (matrix)


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

# Get the shape of the array


shape = arr.shape
print("Shape of the array:", shape) # Output: (2, 3)
Shape of the array: (2, 3)

In [19]: # Create a 1D array


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

# Reshape the array to a 2D array with 2 rows and 3 columns


reshaped_arr = arr.reshape(2, 3)

print("Original array:")
print(arr)

print("\nReshaped array:")
print(reshaped_arr)
Original array:
[1 2 3 4 5 6]

Reshaped array:
[[1 2 3]
[4 5 6]]
In [ ]:

Initialization of Arrays in Numpy


- In NumPy, arrays can be initialized in various ways depending on the
specific requirements of your application.
Here are some common methods for initializing arrays in NumPy:

- 1) Using Python Lists or Tuples


- 2) Using Special Functions
- 3) Using Random Number Generators

In [20]: # 1) Using Python Lists or Tuples:


#) You can initialize a NumPy array using Python lists or tuples by passing them as argum

# Initialize an array from a Python list


arr1 = np.array([1, 2, 3, 4, 5])
print(f"From List {arr1}")
# Initialize an array from a Python tuple
arr2 = np.array((1, 2, 3, 4, 5))
print(f"From Tuple {arr2}")
From List [1 2 3 4 5]
From Tuple [1 2 3 4 5]

In [21]: # 2) Using Special Functions:


# NumPy provides several special functions for initializing arrays with specific values.

# numpy.zeros(): Create an array filled with zeros.


# numpy.ones(): Create an array filled with ones.
# numpy.full(): Create an array filled with a specified value.
# numpy.empty(): Create an array with uninitialized (arbitrary) values.
# numpy.eye(): Create an identity matrix.
# numpy.arange(): Create an array with evenly spaced values within a specified range.
# numpy.linspace(): Create an array with evenly spaced numbers over a specified interval

# Create an array of zeros


zeros_array = np.zeros((3, 3))
print(f"Zeros Array = \n{zeros_array}")
# Create an array of ones
ones_array = np.ones((2, 4))
print(f"\nOnes Array = \n{ones_array}")
# Create an array filled with a specified value
twos_array = np.full((3, 2), 2)
print(f"\nTwos Array = \n{twos_array}")
# Create an identity matrix
identity_matrix = np.eye(3)
print(f"\nIdentity Matrix Array = \n{identity_matrix}")
# Create an array with values from 0 to 9
range_array = np.arange(10)
print(f"\nRange Array = \n{range_array}")
# Create an array with 10 equally spaced values from 0 to 1
linspace_array = np.linspace(0, 1, 10)
print(f"\nLinespace Array = \n{linspace_array}")
Zeros Array =
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

Ones Array =
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]

Twos Array =
[[2 2]
[2 2]
[2 2]]

Identity Matrix Array =


[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

Range Array =
[0 1 2 3 4 5 6 7 8 9]

Linespace Array =
[0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
0.66666667 0.77777778 0.88888889 1. ]

In [22]: # 3) Using Random Number Generators:


# NumPy provides functions for generating arrays with random values.

# numpy.random.rand(): Generate random numbers from a uniform distribution over [0, 1).
# numpy.random.randn(): Generate random numbers from a standard normal distribution.
# numpy.random.randint(): Generate random integers from a specified low to high range.
# numpy.random.random(): Generate random floats in the half-open interval [0.0, 1.0).

# Generate a 3x3 array of random numbers from a uniform distribution


random_uniform_array = np.random.rand(3, 3)
print(f"random_uniform_array = \n{random_uniform_array}")
# Generate a 2x4 array of random numbers from a standard normal distribution
random_normal_array = np.random.randn(2, 4)
print(f"\nrandom_normal_array = \n{random_normal_array}")

# Generate a 4x4 array of random integers from 0 to 9


random_int_array = np.random.randint(0, 10, (4, 4))
print(f"\nrandom_int_array = \n{random_int_array}")
random_uniform_array =
[[0.34682279 0.31900843 0.9707554 ]
[0.83629387 0.1186861 0.27288967]
[0.43580626 0.48837098 0.23386197]]

random_normal_array =
[[-0.1556638 -0.42272671 -0.95054239 -0.40332646]
[-0.77956962 -0.43401801 1.45729616 0.77205238]]

random_int_array =
[[5 4 2 1]
[0 6 3 8]
[4 5 4 3]
[3 2 5 1]]

Accessing Elements of Nd-Array


- Single Element Access
- Slicing
- Boolean Indexing
- Fancy Indexing

In [23]: a=np.array([1,2,3,4,5])
print(f"Array = {a[::-1]}")

b=[1,2,3,4,5]
print(f"List = {b[::-1]}")

# in output we can Observe in Array we have space and in List we have ',' for separation
Array = [5 4 3 2 1]
List = [5, 4, 3, 2, 1]

In [24]: a=np.array([[10,20,30],[40,50,60]])
print(f"Accessing 10,20 elements by using Slicing = \n{a[0,0:2]}")
print(f"Accessing 10,20,40,50 elements by using Slicing = \n{a[0:2,0:2]}")
Accessing 10,20 elements by using Slicing =
[10 20]
Accessing 10,20,40,50 elements by using Slicing =
[[10 20]
[40 50]]

In [25]: a=np.array([[[10,20,30],[40,50,60]],[[1,2,3],[4,5,6]]])
print(f"Accessing 10,20,40,50 elements by using Slicing = \n{a[0,1,0:2]}")
Accessing 10,20,40,50 elements by using Slicing =
[40 50]

In [26]: a=np.array([[[10,20,30],[40,50,60]],[[1,2,3],[4,5,6]]])
# Accessing 50 value
print("Accessing 50 value = ",a[0,1,1])
print("Accessing 2 value = ",a[1,0,1])
Accessing 50 value = 50
Accessing 2 value = 2

In [27]: # Single Element Access : We can access a single element of an ndarray using its indices
# Create a 2D array (matrix)
arr = np.array([[1, 2, 3],
[4, 5, 6]])

# Access the element at row 1, column 2 (0-based indexing)


element = arr[1, 2]

print("Element at index (1, 2):", element) # Output: 6


Element at index (1, 2): 6

In [28]: arr[-1]

Out[28]: array([4, 5, 6])

In [29]: # Slicing : We can slice ndarrays to access a subset of elements along one or more dimen

# Create a 2D array (matrix)


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

# Slice the first row


first_row = arr[0, :]

print("First row:", first_row) # Output: [1 2 3]

# Slice the second column


second_column = arr[:, 1]

print("Second column:", second_column) # Output: [2 5]

# Slice a submatrix
submatrix = arr[:2, 1:]

print("Submatrix:")
print(submatrix)
First row: [1 2 3]
Second column: [2 5]
Submatrix:
[[2 3]
[5 6]]

In [30]: # Boolean Indexing : We can use boolean arrays to index ndarrays and filter elements bas

# Create a 1D array
arr = np.array([1, 2, 3, 4, 5])

# Create a boolean array indicating elements greater than 2


mask = arr > 2

print("Boolean mask:", mask) # Output: [False False True True True]

# Use the boolean mask to filter elements


filtered_arr = arr[mask]

print("Filtered array:", filtered_arr) # Output: [3 4 5]


Boolean mask: [False False True True True]
Filtered array: [3 4 5]

In [31]: # Fancy Indexing : We can use arrays of indices (fancy indexing) to access elements from

# Create a 1D array
arr = np.array([1, 2, 3, 4, 5])

# Create an array of indices


indices = np.array([0, 2, 4])

# Use fancy indexing to access elements


selected_elements = arr[indices]

print("Selected elements:", selected_elements) # Output: [1 3 5]


Selected elements: [1 3 5]

Understanding of Axis Attribute in Numpy


- Row-wise Sorting
- Column-wise Sorting
- One-dimensional Arrays
- Multi-dimensional Arrays
- Understanding Axis in Functions
In [32]: # 1) Row-wise Sorting : Sorting the elements of each row independently.

# Create a 2D array
arr = np.array([[3, 2, 5],
[1, 4, 6],
[7, 0, 2]])

# Sort each row independently


sorted_rows = np.sort(arr, axis=1)

print("Original array:")
print(arr)

print("\nRow-wise sorted array:")


print(sorted_rows)
Original array:
[[3 2 5]
[1 4 6]
[7 0 2]]

Row-wise sorted array:


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

In [33]: # 2) Column-wise Sorting : Sorting the elements of each column independently.

# Create a 2D array
arr = np.array([[3, 2, 5],
[1, 4, 6],
[7, 0, 2]])

# Sort each column independently


sorted_columns = np.sort(arr, axis=0)

print("Original array:")
print(arr)

print("\nColumn-wise sorted array:")


print(sorted_columns)
Original array:
[[3 2 5]
[1 4 6]
[7 0 2]]

Column-wise sorted array:


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

In [34]: # 3) One-dimensional Arrays : For one-dimensional arrays, there is only one axis (axis 0
# Operations along this axis are straightforward, as there's only one dimension to co

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

# Sum of all elements


total_sum = np.sum(arr)
print("Total sum:", total_sum) # Output: 15

# Here, axis is not explicitly specified because there's only one axis (axis 0)
Total sum: 15
In [35]: # 4) Multi-dimensional Arrays : For multi-dimensional arrays, the axis parameter becomes
# Each axis is identified by an integer, where axis 0 corresponds to the first dimens
# to the second dimension, and so on.

arr = np.array([[1, 2, 3],


[4, 5, 6]])

# Sum of elements along axis 0 (sum of each column)


sum_along_axis_0 = np.sum(arr, axis=0)
print("Sum along axis 0:", sum_along_axis_0) # Output: [5 7 9]

# Sum of elements along axis 1 (sum of each row)


sum_along_axis_1 = np.sum(arr, axis=1)
print("Sum along axis 1:", sum_along_axis_1) # Output: [ 6 15]

# Here, axis=0 sums along the rows, and axis=1 sums along the columns
Sum along axis 0: [5 7 9]
Sum along axis 1: [ 6 15]

In [36]: # 5) Understanding Axis in Functions : The axis parameter behaves differently depending
# For functions like np.sum(), np.mean(), np.max(), etc., specifying the axis paramet
# which the operation is performed. However, for functions like np.argmax(), the axis
# along which the maximum value is searched for.

arr = np.array([[1, 2, 3],


[4, 5, 6]])

# Index of maximum value along axis 0 (column-wise)


max_index_axis_0 = np.argmax(arr, axis=0)
print("Index of max along axis 0:", max_index_axis_0) # Output: [1 1 1]

# Index of maximum value along axis 1 (row-wise)


max_index_axis_1 = np.argmax(arr, axis=1)
print("Index of max along axis 1:", max_index_axis_1) # Output: [2 2]

# Here, axis=0 finds the index of the maximum along each column,
# and axis=1 finds the index of the maximum along each row
Index of max along axis 0: [1 1 1]
Index of max along axis 1: [2 2]

NumPy data types


- These are shorthand notations representing various NumPy data types.
Each letter corresponds to a specific data type.
Here's what each letter represents:

- i: Signed integer
- f: Floating-point number
- s: String
- u: Unsigned integer
- M: Datetime
- m: Timedelta
- O: Object
- v: Void
These shorthand notations are commonly used when specifying the data
type of NumPy arrays using the dtype parameter.
For example:
- np.int32 can be abbreviated as i4
- np.float64 can be abbreviated as f8
- np.str_ can be abbreviated as S
- np.uint16 can be abbreviated as u2
- np.datetime64 can be abbreviated as M8
- np.timedelta64 can be abbreviated as m8
- np.object can be abbreviated as O
- np.void can be abbreviated as V

In [37]: # Here's how you can use these abbreviations:

# Create arrays with specified data types using shorthand notations


arr_int = np.array([1, 2, 3], dtype='i4') # Signed integer
arr_float = np.array([1.0, 2.0, 3.0], dtype='f8') # Floating-point number
arr_str = np.array(['a', 'b', 'c'], dtype='S') # String
arr_uint = np.array([1, 2, 3], dtype='u2') # Unsigned integer
arr_datetime = np.array(['2022-01-01', '2022-01-02'], dtype='M') # Datetime
arr_object = np.array([1, 'a', True], dtype='O') # Object

print("Array with signed integer:", arr_int)


print("Array with floating-point number:", arr_float)
print("Array with string:", arr_str)
print("Array with unsigned integer:", arr_uint)
print("Array with datetime:", arr_datetime)
print("Array with object:", arr_object)
Array with signed integer: [1 2 3]
Array with floating-point number: [1. 2. 3.]
Array with string: [b'a' b'b' b'c']
Array with unsigned integer: [1 2 3]
Array with datetime: ['2022-01-01' '2022-01-02']
Array with object: [1 'a' True]

Copy() vs View()
- In NumPy, both copy() and view() are methods used to create a new
array object from an existing array, but they behave differently:

In [38]: # copy() Method : The copy() method creates a deep copy of the array. This means that it
# array object with its own data, separate from the original array. Changes made to the
# array, and vice versa.

# Create an original array


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

# Create a deep copy of the original array


copied_arr = original_arr.copy()

# Modify the copied array


copied_arr[0] = 100

print("Original array:", original_arr) # Output: [1 2 3]


print("Copied array:", copied_arr) # Output: [100 2 3]
Original array: [1 2 3]
Copied array: [100 2 3]

In [39]: # view() Method : The view() method creates a shallow copy of the array. It creates a ne
# view of the same data as the original array. Changes made to the view affect the origi
# However, the view may have a different shape or strides, allowing you to reinterpret t
# Create an original array
original_arr = np.array([1, 2, 3])

# Create a view of the original array


view_arr = original_arr.view()

# Modify the view


view_arr[0] = 100

print("Original array:", original_arr) # Output: [100 2 3]


print("View array:", view_arr) # Output: [100 2 3]
Original array: [100 2 3]
View array: [100 2 3]

Summary:
- copy(): Creates a deep copy of the array, resulting in a new array
with its own data. Changes to the copy do not
affect the original array.
- view(): Creates a shallow copy of the array, resulting in a new array
with a different view of the same data.
Changes to the view affect the original array.

We can Choose between copy() and view() based on your specific requirements. If you need a completely
independent array, use copy(). If you want to manipulate the data in different ways but share memory between
the arrays, use view().

Joining Arrays
- concatenate()
- stack()
- vstack()
- hstack()
- dstack()

In [40]: # concatenate()
a=np.arange(6).reshape(2,3)
print(f"A = \n{a}")
b=np.arange(7,13).reshape(2,3)
print(f"\nB = \n{b}")

print(f"\nConcatenination with Axis=0 = \n{np.concatenate((a,b))}")


print(f"\nConcatenination with Axis=1 = \n{np.concatenate((a,b),axis=1)}")
A =
[[0 1 2]
[3 4 5]]

B =
[[ 7 8 9]
[10 11 12]]

Concatenination with Axis=0 =


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

Concatenination with Axis=1 =


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

In [41]: # stack()

# Create two arrays


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

# Stack arrays along a new axis (axis 0 by default)


result = np.stack((arr1, arr2))

print("Stacked array with np.stack():")


print(result)

result = np.stack((arr1, arr2),axis=1)

print("Stacked array with np.stack():")


print(result)
Stacked array with np.stack():
[[1 2 3]
[4 5 6]]
Stacked array with np.stack():
[[1 4]
[2 5]
[3 6]]

In [42]: # np.vstack() : The np.vstack() function stacks arrays vertically (row-wise).

# Create two arrays


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

# Stack arrays vertically


result = np.vstack((arr1, arr2))

print("Stacked array vertically:")


print(result)
Stacked array vertically:
[[1 2 3]
[4 5 6]]

In [43]: # np.hstack() : The np.hstack() function stacks arrays horizontally (column-wise).

# Create two arrays


arr1 = np.array([[1], [2], [3]])
arr2 = np.array([[4], [5], [6]])
# Stack arrays horizontally
result = np.hstack((arr1, arr2))

print("Stacked array horizontally:")


print(result)
Stacked array horizontally:
[[1 4]
[2 5]
[3 6]]

In [44]: # np.dstack() : The np.dstack() function stacks arrays along the third dimension (depth)

# Create two arrays


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

# Stack arrays along the third dimension


result = np.dstack((arr1, arr2))

print("Stacked array with np.dstack():")


print(result)
Stacked array with np.dstack():
[[[1 5]
[2 6]]

[[3 7]
[4 8]]]

Splitting Arrays in Numpy


- split() to split an array into multiple sub-arrays along a specified
axis.
- array_split() is similar to split() but allows for uneven splits.
- hsplit() to split an array horizontally (along columns).
- vsplit() to split an array vertically (along rows).
- dsplit() to split an array along the third dimension (depth).

In [45]: # split()
arr = np.arange(9)

# Split the array into three sub-arrays


print(np.split(arr, 3))
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]

In [46]: # array_split()
arr = np.arange(10)

# Split the array into three sub-arrays


np.array_split(arr, 3)

Out[46]: [array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]

In [47]: # hsplit()
arr = np.arange(1, 13).reshape(3, 4)

# Split the array horizontally into two sub-arrays


np.hsplit(arr, 2)
Out[47]: [array([[ 1, 2],
[ 5, 6],
[ 9, 10]]),
array([[ 3, 4],
[ 7, 8],
[11, 12]])]

In [48]: arr = np.arange(1, 13).reshape(4, 3)


# Split the array vertically into two sub-arrays
np.vsplit(arr, 2)

Out[48]: [array([[1, 2, 3],


[4, 5, 6]]),
array([[ 7, 8, 9],
[10, 11, 12]])]

In [49]: arr = np.arange(1, 25).reshape(2, 3, 4)

# Split the array along the third dimension into two sub-arrays
np.dsplit(arr, 2)

Out[49]: [array([[[ 1, 2],


[ 5, 6],
[ 9, 10]],

[[13, 14],
[17, 18],
[21, 22]]]),
array([[[ 3, 4],
[ 7, 8],
[11, 12]],

[[15, 16],
[19, 20],
[23, 24]]])]

Search in Numpy
- Finding Elements Meeting Conditions:
- np.where() : Returns the indices of elements in an array where a
given condition is satisfied.
- Boolean Indexing : Creates a boolean array based on a condition
and uses it to filter elements.
- searchsorted()
- Searching for Specific Values:
- np.argmax() : Returns the indices of the maximum and minimum
values in an array.
- np.argmin()
- Array Comparison:
- np.allclose() : Checks if all elements of two arrays are equal
within a tolerance.
- Searching for Specific Values:
- np.isin(): Checks if elements of one array are present in another
array.

In [50]: # np.where()
a=np.arange(10,100,10)
print(a)
print(f"array of Index Numbers = {np.where(a%15==0)}")
arr = np.array([1, 2, 3, 4, 5])
indices = np.where(arr > 3)
print("\nIndices where elements > 3:", indices)
[10 20 30 40 50 60 70 80 90]
array of Index Numbers = (array([2, 5, 8], dtype=int64),)

Indices where elements > 3: (array([3, 4], dtype=int64),)

In [51]: # Boolean Indexing: Creates a boolean array based on a condition and uses it to filter e

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


filtered_arr = arr[arr > 3]
print("Elements > 3:", filtered_arr)
Elements > 3: [4 5]

In [52]: # searchsorted() is a function in NumPy that returns the indices where elements should b
# the sorted order in an array. It is useful for finding the indices where elements woul
# array to maintain its sorted order.

arr = np.array([1, 3, 5, 7, 9])

# Search for the indices where elements should be inserted to maintain sorted order
indices = np.searchsorted(arr, [2, 14, 6, 8])

print("Indices to maintain sorted order:", indices)


Indices to maintain sorted order: [1 5 3 4]

In [53]: # np.argmax() and np.argmin(): Returns the indices of the maximum and minimum values in

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


max_index = np.argmax(arr)
min_index = np.argmin(arr)
print("Index of max value:", max_index)
print("Index of min value:", min_index)
Index of max value: 4
Index of min value: 0

In [54]: # np.allclose(): Checks if all elements of two arrays are equal within a tolerance.
arr1 = np.array([1, 2, 3])
arr2 = np.array([1.001, 2.002, 3.003])
are_close = np.allclose(arr1, arr2, atol=0.01)
print("Arrays are close:", are_close)
Arrays are close: True

In [55]: # np.isin(): Checks if elements of one array are present in another array.
arr = np.array([1, 2, 3, 4, 5])
values = [2, 4, 6]
is_present = np.isin(arr, values)
print("Elements present:", is_present)
Elements present: [False True False True False]

Sort() in Numpy
In [56]: # Ex1
# Create an array
arr = np.array([3, 1, 2, 5, 4])
# Sort the array
sorted_arr = np.sort(arr)

print("Original array:", arr)


print("Sorted array:", sorted_arr)
Original array: [3 1 2 5 4]
Sorted array: [1 2 3 4 5]

In [57]: # Ex2
# Sorting along Axis 0 (Rows) : When sorting along axis 0, each row of the array is trea
# elements within each row are sorted independently.

arr = np.array([[3, 2, 1],


[6, 5, 4],
[9, 8, 7]])

# Sort along axis 0 (rows)


sorted_arr = np.sort(arr, axis=0)

print("Sorted array along axis 0 (rows):")


print(sorted_arr)
Sorted array along axis 0 (rows):
[[3 2 1]
[6 5 4]
[9 8 7]]

In [58]: # Ex3
# Sorting along Axis 1 (Columns) : When sorting along axis 1, each column of the array i
# and the elements within each column are sorted independently.

arr = np.array([[3, 2, 1],


[6, 5, 4],
[9, 8, 7]])

# Sort along axis 1 (columns)


sorted_arr = np.sort(arr, axis=1)

print("Sorted array along axis 1 (columns):")


print(sorted_arr)
Sorted array along axis 1 (columns):
[[1 2 3]
[4 5 6]
[7 8 9]]

In [59]: # Ex4
d=np.dtype([('name','S10'),('perc',float)])
stud=np.array([("abc",90.3),("def",95.5),("ghi",65.3)],dtype=d)
print(stud)

np.sort(stud,order="perc")
[(b'abc', 90.3) (b'def', 95.5) (b'ghi', 65.3)]
Out[59]: array([(b'ghi', 65.3), (b'abc', 90.3), (b'def', 95.5)],
dtype=[('name', 'S10'), ('perc', '<f8')])

Arithmetic Operations on Arrays in Numpy


- Element-wise Arithmetic Operations
- Broadcasting
- Universal Functions (ufuncs)

In [60]: # Element-wise Arithmetic Operations : We can perform arithmetic operations element-wise


# same shape or between an array and a scalar value.

# Create two arrays


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

# Addition
result_add = arr1 + arr2
# Subtraction
result_sub = arr1 - arr2
# Multiplication
result_mul = arr1 * arr2
# Division
result_div = arr1 / arr2
# Exponentiation
result_exp = arr1 ** 2

print("Addition:", result_add)
print("Subtraction:", result_sub)
print("Multiplication:", result_mul)
print("Division:", result_div)
print("Exponentiation:", result_exp)
Addition: [5 7 9]
Subtraction: [-3 -3 -3]
Multiplication: [ 4 10 18]
Division: [0.25 0.4 0.5 ]
Exponentiation: [1 4 9]

In [61]: # Modulo (np.mod() or % operator):


import numpy as np

# Create an array
arr = np.array([10, 20, 30])

# Modulo operation
result_mod = np.mod(arr, 3) # Equivalent to arr % 3

print("Modulo operation:", result_mod)


Modulo operation: [1 2 0]

In [62]: # Power (np.power() or ** operator):


# Power operation
result_power = np.power(arr, 2) # Equivalent to arr ** 2

print("Power operation:", result_power)


Power operation: [100 400 900]

In [63]: # Reciprocal (np.reciprocal()) : Reciprocal operation calculates the reciprocal of each

# Reciprocal operation
result_reciprocal = np.reciprocal(arr)

print("Reciprocal operation:", result_reciprocal)


Reciprocal operation: [0 0 0]

In [64]: # Complex Arithmetic Functions : NumPy also supports complex arithmetic operations such
# imaginary part, and absolute value.
# Create a complex array
arr_complex = np.array([1 + 2j, 3 + 4j, 5 + 6j])

# Complex conjugate
result_conjugate = np.conj(arr_complex)

# Real part
result_real = np.real(arr_complex)

# Imaginary part
result_imag = np.imag(arr_complex)

# Absolute value
result_abs = np.abs(arr_complex)

print("Complex conjugate:", result_conjugate)


print("Real part:", result_real)
print("Imaginary part:", result_imag)
print("Absolute value:", result_abs)
Complex conjugate: [1.-2.j 3.-4.j 5.-6.j]
Real part: [1. 3. 5.]
Imaginary part: [2. 4. 6.]
Absolute value: [2.23606798 5. 7.81024968]

In [65]: # Broadcasting : NumPy allows you to perform arithmetic operations between arrays of dif

# Create an array and a scalar value


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

scalar = 10

# Addition (broadcasting)
result_add_scalar = arr + scalar

print("Addition with scalar:\n", result_add_scalar)


Addition with scalar:
[[11 12 13]
[14 15 16]]

In [66]: # Universal Functions (ufuncs) : NumPy provides universal functions (ufuncs) for perform
# arithmetic operations efficiently.

# Create an array
arr = np.array([1, 2, 3])

# Square root
result_sqrt = np.sqrt(arr)
# Exponential
result_exp = np.exp(arr)
# Trigonometric functions (sin, cos, tan)
result_sin = np.sin(arr)
result_cos = np.cos(arr)
result_tan = np.tan(arr)

print("Square root:", result_sqrt)


print("Exponential:", result_exp)
print("Sine:", result_sin)
print("Cosine:", result_cos)
print("Tangent:", result_tan)
Square root: [1. 1.41421356 1.73205081]
Exponential: [ 2.71828183 7.3890561 20.08553692]
Sine: [0.84147098 0.90929743 0.14112001]
Cosine: [ 0.54030231 -0.41614684 -0.9899925 ]
Tangent: [ 1.55740772 -2.18503986 -0.14254654]

Statistical Functions in Numpy


- NumPy provides a wide range of statistical functions for analyzing
numerical data efficiently. These functions
allow us to compute various statistical measures such as mean, median,
standard deviation, variance, percentile,
and many others. Here are some commonly used statistical functions in
NumPy:
- Measures of Central Tendency
- Mean: Compute the arithmetic mean along the specified axis.
- Median: Compute the median along the specified axis.
- Mode: Compute the mode along the specified axis.
(Note: NumPy doesn't provide a built-in function for
mode calculation.)
- Measures of Dispersion
- Standard Deviation: Compute the standard deviation along the
specified axis.
- Variance: Compute the variance along the specified axis.
- Percentiles
- Percentile
- Min and Max
- Minimum: Compute the minimum value along the specified axis.
- Maximum: Compute the maximum value along the specified axis.
- Summary Statistics
- Sum: Compute the sum of array elements along the specified
axis.
- Cumulative Sum: Compute the cumulative sum of array elements
along the specified axis.
- Correlation and Covariance
- Correlation Coefficient: Compute the correlation coefficient
matrix.
- Covariance Matrix: Compute the covariance matrix.

In [67]: arr=np.array([1,2,3,45,67,3,65,7,34,76,3,2])

In [68]: arr

Out[68]: array([ 1, 2, 3, 45, 67, 3, 65, 7, 34, 76, 3, 2])

In [69]: np.mean(arr, axis=None)

Out[69]: 25.666666666666668

In [70]: np.median(arr, axis=None)

Out[70]: 5.0

In [71]: from scipy.stats import mode


mode(arr)
Out[71]: ModeResult(mode=3, count=3)

In [72]: np.var(arr, axis=None)

Out[72]: 820.8888888888888

In [73]: np.std(arr, axis=None)

Out[73]: 28.65115859592573

In [74]: # percentile
arr = np.array([1, 2, 3, 4, 5])

# Compute the 50th percentile (median) of the array


percentile_50 = np.percentile(arr, 50)

print("50th percentile (median):", percentile_50)


50th percentile (median): 3.0

In [75]: np.min(arr, axis=None)

Out[75]: 1

In [76]: np.max(arr, axis=None)

Out[76]: 5

In [77]: np.sum(arr, axis=None)

Out[77]: 15

In [78]: np.cumsum(arr, axis=None)

Out[78]: array([ 1, 3, 6, 10, 15])

In [79]: np.corrcoef(arr)

Out[79]: 1.0

In [80]: np.cov(arr)

Out[80]: array(2.5)

NumPy Random Number Generation


NumPy offers a comprehensive suite of functions for generating random
numbers, which are useful for a variety of
purposes such as simulations, statistical analysis, and machine learning
experiments. Here's an overview of some
commonly used random number generation functions in NumPy:
- np.random.rand(): Generates random values in a given shape from a
uniform distribution between 0 and 1.
- np.random.randint(): Generates random integers from a specified low
(inclusive) to high (exclusive) range.
- np.random.normal(): Draws random samples from a normal (Gaussian)
distribution with specified mean and SD
- np.random.shuffle(): Modifies a sequence in-place by shuffling its
contents randomly.
- np.random.choice(): Generates a random sample from a given 1-D array
with or without replacement.
- np.random.seed(): Seeds the random number generator to produce
reproducible random numbers.
- np.random.permutation(): Randomly permutes a sequence or returns a
permuted range.
- np.random.uniform(): Draws samples from a uniform distribution within
a specified range.
- np.random.binomial(): Draws samples from a binomial distribution with
specified parameters.
- np.random.poisson(): Draws samples from a Poisson distribution with
specified rate parameter.

In [81]: import numpy as np

In [82]: # np.random.rand(): Generates random values in a given shape from a uniform distribution
# Generate a 2x3 array of random numbers
random_array = np.random.rand(2, 3)
print("Random array from uniform distribution:", random_array)
Random array from uniform distribution: [[0.81790752 0.15824763 0.60906654]
[0.28188703 0.40432175 0.30668917]]

In [83]: # np.random.randint():Generates random integers from a specified low (inclusive) to high


# Generate 5 random integers between 1 and 10
random_integers = np.random.randint(1, 10, size=5)
print("Random integers:", random_integers)
Random integers: [4 9 9 5 2]

In [84]: # np.random.normal():Draws random samples from a normal (Gaussian) distribution with spe
# Generate 5 random numbers from a normal distribution with mean 0 and standard deviatio
random_normal = np.random.normal(0, 1, size=5)
print("Random values from normal distribution:", random_normal)
Random values from normal distribution: [ 0.44586891 0.21942117 -1.20103574 -1.16410359
-1.11527723]

In [85]: # np.random.shuffle(): Modifies a sequence in-place by shuffling its contents randomly.


# Shuffle a list
arr = [1, 2, 3, 4, 5]
np.random.shuffle(arr)
print("Shuffled array:", arr)
Shuffled array: [3, 4, 1, 2, 5]

In [86]: # np.random.choice(): Generates a random sample from a given 1-D array with or without r
# Generate a random sample from a given array
arr = np.array([1, 2, 3, 4, 5])
random_sample = np.random.choice(arr, size=3, replace=False)
print("Random sample:", random_sample)
Random sample: [1 5 3]

In [87]: # np.random.seed():Seeds the random number generator to produce reproducible random numb
# Seed the random number generator
np.random.seed(0)
random_value = np.random.rand()
print("Random value with seed:", random_value)
Random value with seed: 0.5488135039273248
In [88]: # np.random.permutation(): Randomly permutes a sequence or returns a permuted range.
# Permute a sequence
arr = np.array([1, 2, 3, 4, 5])
permuted_arr = np.random.permutation(arr)
print("Permuted array:", permuted_arr)
Permuted array: [5 3 2 4 1]

In [89]: # np.random.uniform(): Draws samples from a uniform distribution within a specified rang
# Generate 5 random numbers from a uniform distribution [1, 10)
random_uniform = np.random.uniform(1, 10, size=5)
print("Random values from uniform distribution:", random_uniform)
Random values from uniform distribution: [6.81304702 4.9382849 9.02595701 9.67296484 4.
45097367]

In [90]: # np.random.binomial():Draws samples from a binomial distribution with specified paramet


# Generate 5 random samples from a binomial distribution with n=10 and p=0.5
random_binomial = np.random.binomial(10, 0.5, size=5)
print("Random samples from binomial distribution:", random_binomial)
Random samples from binomial distribution: [6 5 5 7 3]

In [91]: # np.random.poisson(): Draws samples from a Poisson distribution with specified rate par
# Generate 5 random samples from a Poisson distribution with lambda=2.0
random_poisson = np.random.poisson(2.0, size=5)
print("Random samples from Poisson distribution:", random_poisson)
Random samples from Poisson distribution: [0 0 7 1 3]

In [ ]:

Basic Problem Solving


In [92]: # 1) Create a NumPy array of zeros with shape (3, 4).

import numpy as np

x=np.zeros((3,4))
x

Out[92]: array([[0., 0., 0., 0.],


[0., 0., 0., 0.],
[0., 0., 0., 0.]])

In [1]: # 2) Create a NumPy array of ones with shape (2, 3, 4).


import numpy as np
x=np.ones((2,3,4))
x

Out[1]: array([[[1., 1., 1., 1.],


[1., 1., 1., 1.],
[1., 1., 1., 1.]],

[[1., 1., 1., 1.],


[1., 1., 1., 1.],
[1., 1., 1., 1.]]])

In [3]: # 3) Create a NumPy array with values from 0 to 9.


x=np.arange(0,10)
x
Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [4]: # 4) Create a NumPy array with values from 10 to 29.


x=np.arange(10,30)
x

Out[4]: array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29])

In [6]: # 5) Create a 3x3 identity matrix.


x=np.eye(3)
x

Out[6]: array([[1., 0., 0.],


[0., 1., 0.],
[0., 0., 1.]])

In [9]: # 6) Create a random NumPy array of shape (2, 3).


x=np.random.rand(2,3)
x

Out[9]: array([[0.08686746, 0.01323134, 0.21084767],


[0.08998506, 0.95201384, 0.21804003]])

In [18]: # 7) Reshape the array from problem 6 into shape (3, 2).

temp=x
print(f"Before Reshape = \n{temp}")

y=np.reshape(x,(3,2))
print(f"\nAfter Reshape = \n{y}")
Before Reshape =
[[0.08686746 0.01323134 0.21084767]
[0.08998506 0.95201384 0.21804003]]

After Reshape =
[[0.08686746 0.01323134]
[0.21084767 0.08998506]
[0.95201384 0.21804003]]

In [23]: # 3) Create a NumPy array with values from 0 to 9.


# 8) Sum all elements in the array from problem 3.

# 3rd Problem
x=np.arange(0,10)
print(f"the NUMBERS are = {x}")

# 8th Problem
total=np.sum(x)
print(f"sum of Total Numbers are = {total}")
the NUMBERS are = [0 1 2 3 4 5 6 7 8 9]
sum of Total Numbers are = 45

In [24]: # 9) Find the maximum value in the array from problem 4.

# 4th Problem
x=np.arange(10,30)
x

# 9th Problem

np.max(x)
Out[24]: 29

In [35]: # 10) Compute the dot product of two arrays: [1, 2, 3] and [4, 5, 6].

one=np.array([1, 2, 3])
two=np.array([4, 5, 6])
tot=np.dot(one,two)
print(f"First Method = {tot}")

print(f"Second Method = {one@two}")


First Method = 32
Second Method = 32

In [42]: # 11) Create a NumPy array from a Python list


lis=[1,2,3,4,5]
print(f"List = {lis}")
nump=np.array(lis)
print(f"List Converted Array = {nump}")
List = [1, 2, 3, 4, 5]
List Converted Array = [1 2 3 4 5]

In [50]: # 12) Create a NumPy array of evenly spaced values between 1 and 10.
print(f"Evenly spaced Values are = {np.linspace(1,10,10)}")
Evenly spaced Values are = [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]

In [47]: evenly_spaced_array = np.linspace(1, 10, num=10)


print(evenly_spaced_array)
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]

In [55]: # 13) Reverse the order of elements in a NumPy array.


x=np.arange(2,6)
print(f"Original Array = {x}")
y=x[::-1]
print(f"Reverse Array = {y}")
Original Array = [2 3 4 5]
Reverse Array = [5 4 3 2]

In [67]: # 14) Extract all even numbers from a NumPy array.


x=np.arange(1,21)
print(f"First Method = {[i for i in x if i%2==0]}")
print(f"Second Method = {x[x % 2 == 0]}")
First Method = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Second Method = [ 2 4 6 8 10 12 14 16 18 20]

In [70]: # 15) Calculate the mean, median, and standard deviation of elements in a NumPy array.
x=np.array([1,2,3,4,5,23,9,56,23,6.34])

print(f"Mean = {np.mean(x)}")
print(f"Median = {np.median(x)}")
print(f"SD = {np.std(x)}")
Mean = 13.234
Median = 5.67
SD = 16.18273166063134

In [72]: # Normalize a NumPy array.


import numpy as np

# Create a NumPy array


arr = np.array([1, 2, 3, 4, 5])
# Normalize the array
normalized_arr = (arr - np.mean(arr)) / np.std(arr)
print(normalized_arr)
[-1.41421356 -0.70710678 0. 0.70710678 1.41421356]

In [73]: # Find the unique elements and their counts in a NumPy array
import numpy as np

# Create a NumPy array


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

# Find unique elements and their counts


unique_elements, counts = np.unique(arr, return_counts=True)
print("Unique elements:", unique_elements)
print("Counts:", counts)
Unique elements: [1 2 3 4 5]
Counts: [2 2 2 2 1]

In [ ]:

You might also like