NumPy Cheat Sheet

NumPy is a powerful numerical computing library in Python. Below is a NumPy cheat sheet covering common array operations and functionalities:

Basics

Install NumPy:

pip install numpy

Import NumPy:

import numpy as np

Creating Arrays

Create an Array:

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

Zeros Array:

zeros_arr = np.zeros((2, 3))

Ones Array:

ones_arr = np.ones((3, 2))

Identity Matrix:

identity_matrix = np.eye(3)

Random Array:

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

Array Operations

Array Shape:

shape = arr.shape

Reshape Array:

reshaped_arr = arr.reshape((3, 1))

Transpose Array:

transposed_arr = arr.T

Accessing Elements:

element = arr[0, 1]

Slicing:

sub_array = arr[1:3, :]

Array Concatenation:

concat_arr = np.concatenate((arr1, arr2), axis=0)

Element-wise Operations:

result = arr1 * arr2

Matrix Multiplication:

matrix_mult = np.dot(matrix1, matrix2)

Mathematical Functions

Sum of Array:

total_sum = np.sum(arr)

Mean of Array:

mean_value = np.mean(arr)

Standard Deviation:

std_dev = np.std(arr)

Element-wise Square Root:

sqrt_arr = np.sqrt(arr)

Universal Functions (ufunc)

Element-wise Exponential:

exp_arr = np.exp(arr)

Element-wise Logarithm:

log_arr = np.log(arr)

Linear Algebra

Matrix Determinant:

det_value = np.linalg.det(matrix)

Matrix Inverse:

inv_matrix = np.linalg.inv(matrix)

Eigenvalues and Eigenvectors:

eigenvalues, eigenvectors = np.linalg.eig(matrix)

Statistics

Correlation Coefficient:

correlation = np.corrcoef(arr1, arr2)

Histogram:

hist, bins = np.histogram(data, bins=10)

File Handling

Load from Text File:

data = np.loadtxt('data.txt', delimiter=',')

Save to Text File:

np.savetxt('output.txt', data, delimiter=',')

This cheat sheet provides a quick reference for common NumPy operations and functionalities. For more detailed information, refer to the official NumPy documentation.