- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Introduction
NumPy is a fundamental library in Python used for scientific computing and data analysis. It stands for “Numerical Python” and provides powerful tools for working with multi-dimensional arrays and matrices, along with a vast collection of mathematical functions to operate on these arrays efficiently.
Slicing and Indexing using the NumPy library
Slicing and indexing are fundamental operations in NumPy that allow you to access and manipulate specific elements or subsets of an array.
Indexing:
- Single Element: You can access a single element of an array by specifying its index using square brackets.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[0])
# Output: 1
- Multiple Elements: You can access multiple elements of an array by passing a list or an array of indices inside the square brackets.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
indices = [0, 2, 4]
print(arr[indices])
# Output: [1 3 5]
Slicing:
- Basic Slicing: You can use slicing to extract a portion of an array by specifying the start and end indices, separated by a colon inside the square brackets.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Elements from index 1 to 3 (exclusive)
sliced_arr = arr[1:4]
print(sliced_arr)
# Output: [2 3 4]
- Step Slicing: You can specify a step value to slice every nth element from the array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Elements with a step of 2
sliced_arr = arr[::2]
print(sliced_arr)
# Output: [1 3 5]
- Negative Indices: Negative indices allow you to slice from the end of the array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Elements from the third-last to the second-last
sliced_arr = arr[-3:-1]
print(sliced_arr)
# Output: [3 4]
- Slicing Multi-dimensional Arrays: You can slice multi-dimensional arrays using multiple indexing and slicing operations.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Rows from index 1 onwards, columns up to index 1 (exclusive)
sliced_arr = arr[1:, :2]
print(sliced_arr)
# Output:
[[4 5]
[7 8]]
Python Numpy functions
- np.array(): Create a NumPy array from a Python list or tuple.
Syntax: np.array(object, dtype=None, copy=True, order=’K’, subok=False, ndmin=0)
# Example:
import numpy as np
# Create a NumPy array from a Python list
my_list = [1, 2, 3, 4, 5]
my_array = np.array(my_list)
print(my_array)
# Output: [1 2 3 4 5]
- np.arange(): Create an array with evenly spaced values.
Syntax: np.arange([start,] stop[, step,], dtype=None)
# Example:
import numpy as np
# Create an array with values from 0 to 9
my_array = np.arange(10)
print(my_array)
# Output: [0 1 2 3 4 5 6 7 8 9]
- np.zeros(): Create an array filled with zeros.
Syntax: np.zeros(shape, dtype=float, order=’C’)
# Example:
import numpy as np
# Create a 1D array filled with zeros
my_array = np.zeros(5)
print(my_array)
# Output: [0. 0. 0. 0. 0.]
- np.ones(): Create an array filled with ones.
Syntax: np.ones(shape, dtype=None, order=’C’)
# Example:
import numpy as np
# Create a 2D array filled with ones
my_array = np.ones((3, 2))
print(my_array)
# Output:
# [[1. 1.]
# [1. 1.]
# [1. 1.]]
- np.linspace(): Create an array with a specified number of evenly spaced values.
Syntax: np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
# Example:
import numpy as np
# Create an array with 5 evenly spaced values between 0 and 1
my_array = np.linspace(0, 1, 5)
print(my_array)
# Output: [0. 0.25 0.5 0.75 1. ]
- np.eye(): Create an identity matrix.
Syntax: np.eye(N, M=None, k=0, dtype=float, order=’C’)
# Example:
import numpy as np
# Create a 3×3 identity matrix
my_array = np.eye(3)
print(my_array)
# Output:
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]
- np.random.rand(): Generate random values from a uniform distribution.
Syntax: np.random.rand(d0, d1, …, dn)
# Example:
import numpy as np
# Generate a 2×2 array of random values from a uniform distribution
my_array = np.random.rand(2, 2)
print(my_array)
# Output:
[[0.64822645 0.03382209]
[0.45753694 0.67940323]]
- np.random.randn(): Generate random values from a standard normal distribution.
Syntax: np.random.randn(d0, d1, …, dn)
# Example::
import numpy as np
# Generate a 3×3 array of random values from a standard normal distribution
my_array = np.random.randn(3, 3)
print(my_array)
# Output:
[[ 0.21372011 -0.76571721 0.54756781]
[ 0.95714164 -0.12939294 -0.57725997]
[-0.28264262 -0.45355784 -0.33564826]]
- np.random.randint(): Generate random integers within a specified range.
Syntax: np.random.randint(low, high=None, size=None, dtype=int)
# Example:
import numpy as np
# Generate a 1D array of 5 random integers between 0 and 9
my_array = np.random.randint(0, 10, 5)
print(my_array)
# Output:
[4 7 1 2 9]
10. np.shape(): Get the dimensions of an array. Syntax: np.shape(array)
# Example:
import numpy as np
# Get the dimensions of an array
my_array = np.array([[1, 2, 3], [4, 5, 6]])
shape = np.shape(my_array)
print(shape)
# Output: (2, 3)
- np.reshape(): Reshape an array to a specified shape.
Syntax: np.reshape(array, newshape, order=’C’)
# Example::
import numpy as np
# Reshape a 1D array into a 2D array
my_array = np.array([1, 2, 3, 4, 5, 6])
reshaped_array = np.reshape(my_array, (2, 3))
print(reshaped_array)
# Output:
[[1 2 3]
[4 5 6]]
- np.concatenate(): Join arrays along a specified axis.
Syntax: np.concatenate((array1, array2, …), axis=0)
# Example::
import numpy as np
# Concatenate two arrays along the first axis
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6]])
concatenated_array = np.concatenate((array1, array2), axis=0)
print(concatenated_array)
# Output:
[[1 2]
[3 4]
[5 6]]
- np.split(): Split an array into multiple sub-arrays.
Syntax: np.split(array, indices_or_sections, axis=0)
# Example::
import numpy as np
# Split an array into three sub-arrays
my_array = np.array([1, 2, 3, 4, 5, 6])
split_array = np.split(my_array, 3)
print(split_array)
# Output:
[array([1, 2]), array([3, 4]), array([5, 6])]
- np.max(): Find the maximum value in an array.
Syntax: np.max(array, axis=None, out=None, keepdims=False, initial=None)
# Example::
import numpy as np
# Find the maximum value in an array
my_array = np.array([1, 5, 3, 9, 2])
max_value = np.max(my_array)
print(max_value)
# Output: 9
- np.min(): Find the minimum value in an array.
Syntax: np.min(array, axis=None, out=None, keepdims=False, initial=None)
# Example::
import numpy as np
# Find the minimum value in an array
my_array = np.array([1, 5, 3, 9, 2])
min_value = np.min(my_array)
print(min_value)
# Output: 1
- np.mean(): Compute the arithmetic mean of an array.
Syntax: np.mean(array, axis=None, dtype=None, out=None, keepdims=False)
# Example:
import numpy as np
# Compute the mean of an array
my_array = np.array([1, 2, 3, 4, 5])
mean_value = np.mean(my_array)
print(mean_value)
# Output: 3.0
- np.median(): Compute the median of an array.
Syntax: np.median(array, axis=None, out=None, overwrite_input=False)
# Example:
import numpy as np
# Compute the median of an array
my_array = np.array([1, 3, 2, 4, 5])
median_value = np.median(my_array)
print(median_value)
# Output: 3.0
- np.std(): Compute the standard deviation of an array.
Syntax: np.std(array, axis=None, dtype=None, out=None, ddof=0, keepdims=False)
# Example:
import numpy as np
# Compute the standard deviation of an array
my_array = np.array([1, 2, 3, 4, 5])
std_value = np.std(my_array)
print(std_value)
# Output: 1.4142135623730951
- np.sum(): Compute the sum of array elements.
Syntax: np.sum(array, axis=None, dtype=None, out=None, keepdims=False, initial=0)
# Example:
import numpy as np
# Compute the sum of array elements
my_array = np.array([1, 2, 3, 4, 5])
sum_value = np.sum(my_array)
print(sum_value)
# Output: 15
- np.abs():Compute the absolute values of array elements.
Syntax: np.abs(array)
# Example:
import numpy as np
# Compute the absolute values of array elements
my_array = np.array([-1, -2, 3, -4, 5])
abs_values = np.abs(my_array)
print(abs_values)
# Output: [1 2 3 4 5]
- np.exp(): Compute the exponential of array elements.
Syntax: np.exp(array)
# Example::
import numpy as np
# Compute the exponential of array elements
my_array = np.array([1, 2, 3])
exp_values = np.exp(my_array)
print(exp_values)
# Output: [ 2.71828183 7.3890561 20.08553692]
- np.log(): Compute the natural logarithm of array elements.
Syntax: np.log(array)
# Example:
import numpy as np
# Compute the natural logarithm of array elements
my_array = np.array([1, np.e, np.e**2])
log_values = np.log(my_array)
print(log_values) # Output: [0. 1. 2.]
- np.sin(): Compute the sine of array elements.
Syntax: np.sin(array)
# Example:
import numpy as np
# Compute the sine of array elements
my_array = np.array([0, np.pi/2, np.pi])
sin_values = np.sin(my_array)
print(sin_values)
# Output: [0.0000000e+00 1.0000000e+00 1.2246468e-16]
- np.cos(): Compute the cosine of array elements.
Syntax: np.cos(array)
# Example:
import numpy as np
# Compute the cosine of array elements
my_array = np.array([0, np.pi/2, np.pi])
cos_values = np.cos(my_array)
print(cos_values)
# Output: [ 1.000000e+00 6.123234e-17 -1.000000e+00]
- np.tan(): Compute the tangent of array elements.
Syntax: np.tan(array)
# Example:
import numpy as np
# Compute the tangent of array elements
my_array = np.array([0, np.pi/4, np.pi/2])
tan_values = np.tan(my_array)
print(tan_values)
# Output: [0.00000000e+00 1.00000000e+00 1.63312394e+16]
- np.dot(): Compute the dot product of two arrays.
Syntax: np.dot(a, b, out=None)
# Example:
import numpy as np
# Compute the dot product of two arrays
array1 = np.array([1, 2])
array2 = np.array([3, 4])
dot_product = np.dot(array1, array2)
print(dot_product)
# Output: 11
- np.transpose(): Transpose the dimensions of an array.
Syntax: np.transpose(array, axes=None)
# Example:
import numpy as np
# Transpose the dimensions of an array
my_array = np.array([[1, 2], [3, 4]])
transposed_array = np.transpose(my_array)
print(transposed_array)
# Output:
[[1 3]
[2 4]]
- np.sort(): Sort an array.
Syntax: np.sort(array, axis=-1, kind=None, order=None)
# Example:
import numpy as np
# Sort an array
my_array = np.array([3, 1, 4, 2, 5])
sorted_array = np.sort(my_array)
print(sorted_array)
# Output: [1 2 3 4 5]
- np.unique(): Find the unique elements of an array.
Syntax: np.unique(array, return_index=False, return_inverse=False, return_counts=False, axis=None)
# Example:
import numpy as np
# Find the unique elements of an array
my_array = np.array([1, 2, 1, 3, 2, 4])
unique_values = np.unique(my_array)
print(unique_values)
# Output: [1 2 3 4]
- np.argmax(): Find the indices of the maximum values in an array.
Syntax: np.argmax(array, axis=None, out=None)
# Example:
import numpy as np
# Find the indices of the maximum values in an array
my_array = np.array([3, 1, 4, 2, 5])
max_index = np.argmax(my_array)
print(max_index)
# Output: 4
- np.argmin(): Find the indices of the minimum values in an array.
Syntax: np.argmin(array, axis=None, out=None)
# Example:
import numpy as np
# Find the indices of the minimum values in an array
my_array = np.array([3, 1, 4, 2, 5])
min_index = np.argmin(my_array)
print(min_index)
# Output: 1
- np.where(): Return the indices of array elements that satisfy a condition.
Syntax: np.where(condition, x, y)
# Example:
import numpy as np
# Return the indices of array elements that satisfy a condition
my_array = np.array([1, 2, 3, 4, 5])
indices = np.where(my_array > 2)
print(indices)
# Output: (array([2, 3, 4]),)
- np.any():Check if any element in an array satisfies a condition.
Syntax: np.any(array, axis=None, out=None, keepdims=False)
# Example:
import numpy as np
# Check if any element in an array satisfies a condition
my_array = np.array([1, 2, 3, 4, 5])
has_positive = np.any(my_array > 0)
print(has_positive)
# Output: True
- np.all(): Check if all elements in an array satisfy a condition.
Syntax: np.all(array, axis=None, out=None, keepdims=False)
# Example:
import numpy as np
# Check if all elements in an array satisfy a condition
my_array = np.array([1, 2, 3, 4, 5])
all_positive = np.all(my_array > 0)
print(all_positive)
# Output: True
- np.isnan(): Check for NaN (Not a Number) values in an array.
Syntax: np.isnan(array)
# Example:
import numpy as np
# Check for NaN (Not a Number) values in an array
my_array = np.array([1, np.nan, 3, np.nan])
has_nan = np.isnan(my_array)
print(has_nan)
# Output: [False True False True]
- np.logical_and(): Perform element-wise logical AND operation on arrays.
Syntax: np.logical_and(array1, array2)
# Example:
import numpy as np
# Perform element-wise logical AND operation on arrays
array1 = np.array([True, False, True, False])
array2 = np.array([True, True, False, False])
result = np.logical_and(array1, array2)
print(result)
# Output: [ True False False False]
- np.logical_or(): Perform element-wise logical OR operation on arrays.
Syntax: np.logical_or(array1, array2)
# Example:
import numpy as np
# Perform element-wise logical OR operation on arrays
array1 = np.array([True, False, True, False])
array2 = np.array([True, True, False, False])
result = np.logical_or(array1, array2)
print(result)
# Output: [ True True True False]
- np.logical_not(): Perform element-wise logical NOT operation on an array.
Syntax: np.logical_not(array)
# Example:
import numpy as np
# Perform element-wise logical NOT operation on an array
my_array = np.array([True, False, True, False])
result = np.logical_not(my_array)
print(result)
# Output: [False True False True]
- np.sinh(): Compute the hyperbolic sine of array elements.
Syntax: np.sinh(array)
# Example:
import numpy as np
# Compute the hyperbolic sine of array elements
my_array = np.array([0, 1, 2])
sinh_values = np.sinh(my_array)
print(sinh_values)
# Output: [ 0. 1.17520119 3.62686041]
- np.cosh(): Compute the hyperbolic cosine of array elements.
Syntax: np.cosh(array)
# Example:
import numpy as np
# Compute the hyperbolic cosine of array elements
my_array = np.array([0, 1, 2])
cosh_values = np.cosh(my_array)
print(cosh_values)
# Output: [ 1. 1.54308063 3.76219569]
- np.tanh(): Compute the hyperbolic tangent of array elements.
Syntax: np.tanh(array)
# Example:
import numpy as np
# Compute the hyperbolic tangent of array elements
my_array = np.array([0, 1, 2])
tanh_values = np.tanh(my_array)
print(tanh_values)
# Output: [0. 0.76159416 0.96402758]
- np.arcsin(): Compute the inverse sine of array elements.
Syntax: np.arcsin(array)
# Example:
import numpy as np
# Compute the inverse sine of array elements
my_array = np.array([0, 0.5, 1])
arcsin_values = np.arcsin(my_array)
print(arcsin_values)
# Output: [0. 0.52359878 1.57079633]
- np.arccos(): Compute the inverse cosine of array elements.
Syntax: np.arccos(array)
# Example:
import numpy as np
# Compute the inverse cosine of array elements
my_array = np.array([0, 0.5, 1])
arccos_values = np.arccos(my_array)
print(arccos_values)
# Output: [1.57079633 1.04719755 0.]
- np.arctan(): Compute the inverse tangent of array elements.
Syntax: np.arctan(array)
# Example:
import numpy as np
# Compute the inverse tangent of array elements
my_array = np.array([0, 1, np.inf])
arctan_values = np.arctan(my_array)
print(arctan_values)
# Output: [0. 0.78539816 1.57079633]
- np.pi: A constant representing the value of pi (π). A constant representing the value of pi (π)
# Example:
import numpy as np
# Use the constant pi
radius = 1.0
circumference = 2 * np.pi * radius
print(circumference)
# Output: 6.283185307179586
46. np.e: A constant representing the value of Euler’s number (e). A constant representing the value of Euler’s number (e)
# Example::
import numpy as np
# Use the constant e
exponent = 1.0
result = np.exp(exponent)
print(result)
# Output: 2.718281828459045
- np.log10(): Compute the base-10 logarithm of array elements.
Syntax: np.log10(array)
# Example:
import numpy as np
# Compute the base-10 logarithm of array elements
my_array = np.array([1, 10, 100])
log10_values = np.log10(my_array)
print(log10_values)
# Output: [0. 1. 2.]
- np.floor(): Round down array elements to the nearest integer.
Syntax: np.floor(array)
# Example:
import numpy as np
# Round down array elements to the nearest integer
my_array = np.array([1.2, 2.7, 3.5])
floor_values = np.floor(my_array)
print(floor_values)
# Output: [1. 2. 3.]
- np.ceil(): Round up array elements to the nearest integer.
Syntax: np.ceil(array)
# Example:
import numpy as np
# Round up array elements to the nearest integer
my_array = np.array([1.2, 2.7, 3.5])
ceil_values = np.ceil(my_array)
print(ceil_values)
# Output: [2. 3. 4.]
- np.isclose(): Check if two arrays are element-wise approximately equal.
Syntax: np.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
# Example:
import numpy as np
# Check if two arrays are element-wise approximately equal
array1 = np.array([1.0, 2.0, 3.0])
array2 = np.array([1.1, 2.2, 3.3])
is_close = np.isclose(array1, array2, rtol=0.1, atol=0.1)
print(is_close)
# Output: [ True True True]
51. np.correlate(): Compute the cross-correlation of two arrays.
Syntax: np.correlate(a, v, mode=’valid’)
# Example:
import numpy as np
# Compute the cross-correlation of two arrays
a = np.array([1, 2, 3, 4, 5])
v = np.array([0, 1, 0.5])
correlation = np.correlate(a, v, mode=’valid’)
print(correlation)
# Output: [4.5 6. 8.5]
- np.cov(): Compute the covariance matrix of an array.
Syntax: np.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)
# Example:
import numpy as np
# Compute the covariance matrix of an array
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
cov_matrix = np.cov(data, rowvar=False)
print(cov_matrix)
# Output:
[[6. 6. 6.]
[6. 6. 6.]
[6. 6. 6.]]