Numpy
Numpy
1. Introduction to NumPy
NumPy (Numerical Python) is a powerful library for numerical computations in
Python.
It provides support for large multi-dimensional arrays and matrices, along with
a collection of mathematical functions to operate on these arrays.
2. Installation
bash
Copy code
pip install numpy
python
Copy code
import numpy as np
3. Creating Arrays
From Lists:
python
Copy code
arr = np.array([1, 2, 3])
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
Using Functions:
Numpy 1
python
Copy code
zeros = np.zeros((2, 3)) # 2x3 array of zeros
ones = np.ones((2, 3)) # 2x3 array of ones
empty = np.empty((2, 3)) # 2x3 uninitialized arr
ay
arange = np.arange(0, 10, 2) # Array of [0, 2, 4, 6,
8]
linspace = np.linspace(0, 1, 5) # 5 evenly spaced numbe
rs between 0 and 1
4. Array Attributes
Dimensions:
python
Copy code
arr.ndim # Number of dimensions
python
Copy code
arr.shape # Shape of the array
arr.size # Total number of elements
Data Type:
python
Copy code
Numpy 2
arr.dtype # Data type of elements
5. Reshaping Arrays
python
Copy code
arr = np.arange(1, 7) # [1 2 3 4 5 6]
reshaped = arr.reshape((2, 3)) # [[1 2 3], [4 5 6]]
python
Copy code
arr[0] # First element
arr[-1] # Last element
2D Arrays:
python
Copy code
arr_2d[0, 1] # Element in first row, second column
arr_2d[:, 1] # All rows, second column
arr_2d[1, :] # Second row, all columns
Slicing:
python
Copy code
arr[1:4] # Elements from index 1 to 3
Numpy 3
arr[::2] # Every other element
7. Array Operations
Element-wise Operations:
python
Copy code
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
sum = arr1 + arr2 # [5, 7, 9]
product = arr1 * arr2 # [4, 10, 18]
scalar_mult = arr1 * 2 # [2, 4, 6]
Mathematical Functions:
python
Copy code
np.sqrt(arr1) # Square root
np.exp(arr1) # Exponential
np.sin(arr1) # Sine
8. Linear Algebra
python
Copy code
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.array([[5, 6], [7, 8]])
dot_product = np.dot(mat1, mat2) # Matrix multiplication
transpose = mat1.T # Transpose of the matri
Numpy 4
x
python
Copy code
inv_mat = np.linalg.inv(mat1)
det_mat = np.linalg.det(mat1)
9. Broadcasting
Broadcasting allows arithmetic operations on arrays of different shapes.
python
Copy code
arr = np.array([1, 2, 3])
add_scalar = arr + 2 # [3, 4, 5]
add_array = arr + np.array([1]) # [2, 3, 4]
10. Aggregations
Basic Statistical Operations:
python
Copy code
arr = np.array([1, 2, 3, 4, 5])
arr.sum() # Sum of all elements
arr.mean() # Mean value
arr.std() # Standard deviation
arr.min() # Minimum value
arr.max() # Maximum value
Numpy 5
Axis-wise Operations:
python
Copy code
arr_2d = np.array([[1, 2], [3, 4]])
arr_2d.sum(axis=0) # Sum of each column [4, 6]
arr_2d.sum(axis=1) # Sum of each row [3, 7]
python
Copy code
rand_arr = np.random.rand(3, 2) # 3x2 array with rand
om numbers between 0 and 1
rand_int = np.random.randint(0, 10, 5) # Array of 5 random i
ntegers between 0 and 9
python
Copy code
arr = np.array([1, 2, 3, 4, 5])
bool_idx = arr > 3 # [False, False, Fals
e, True, True]
filtered_arr = arr[bool_idx] # [4, 5]
Fancy Indexing:
python
Copy code
Numpy 6
arr = np.array([10, 20, 30, 40, 50])
indices = [1, 3]
arr[indices] # [20, 40]
python
Copy code
arr = np.array([1, 2, 3])
view = arr.view()
view[0] = 7
print(arr) # [7, 2, 3]
python
Copy code
copy = arr.copy()
copy[0] = 1
print(arr) # [7, 2, 3]
python
Copy code
np.save('array.npy', arr)
loaded_arr = np.load('array.npy')
Numpy 7
Text Files:
python
Copy code
np.savetxt('array.txt', arr, delimiter=',')
loaded_txt_arr = np.loadtxt('array.txt', delimiter=',')
Use .astype to convert data types if you need to optimize memory usage.
When performing operations that modify the original array, ensure that’s your
intention, as some methods act in-place.
python
Copy code
data = np.array([1.0, 2.0, 3.0])
adjusted_data = data * 2.5 + 3
Normalizing Data:
python
Copy code
data = np.array([5, 10, 15])
Numpy 8
normalized = (data - data.min()) / (data.max() - data.min
())
python
Copy code
arr = np.array([1, 2, 2, 3, 4, 4, 4])
unique_elements = np.unique(arr)
Numpy 9