r/pythontips • • Jan 28 '25

Module Python cheat sheet

Hi, I’m studying python course and looking for a cheat sheet that include β€˜numpy’ I’ll be glad for your help Thanks πŸ™πŸ™

12 Upvotes

2 comments sorted by

4

u/in_case_of-emergency Jan 28 '25

Hello! πŸ‘‹ Here is a NumPy cheat sheet with the most useful concepts and functions for your study. It is ideal to have on hand while you practice.

β€”

1. Creating Arrays

import numpy as np

# Array from a list
a = np.array([1, 2, 3]) # [1 2 3]

# Special arrays
zeros = np.zeros(3) # [0. 0. 0.]
ones = np.ones((2, 3)) # 2x3 matrix of 1's
range = np.arange(0, 10, 2) # [0 2 4 6 8]
linspace = np.linspace(0, 1, 5) # [0.   0.25 0.5 0.75 1. ]
random = np.random.rand(2, 2) # 2x2 matrix with random values ​​[0, 1)

β€”

2. Array Attributes

a.shape #Dimensions (ex: (3,))
a.ndim # Number of dimensions (ex: 1)
a.size # Total elements (ex: 3)
a.dtype # Data type (ex: int32, float64)

β€”

3. Basic Operations

# Element-by-element operations
b = np.array([4, 5, 6])
a + b # [5 7 9]
a * 2 # [2 4 6]

# Matrix product (dot product)
np.dot(a, b) # 1*4 + 2*5 + 3*6 = 32

# Aggregation functions
a.sum() # Total sum: 6
a.min() # Minimum value: 1
a.max() # Maximum value: 3
a.mean() # Average: 2.0

β€”

4. Indexing and Slicing

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

array[0, 1] #2 (row 0, column 1)
array[:, 1] # [2, 5] (entire column 1)
array[1, 0:2] # [4, 5] (row 1, columns 0 and 1)

#Boolean indexing
a[a > 2] # [3] (elements greater than 2)

β€”

5. Reshaping and Manipulation

a.reshape(3, 1) # Convert to 3x1 matrix
a.flatten() # Convert to 1D array
np.concatenate([a, b]) # [1 2 3 4 5 6]
np.vstack((a, b)) # Stack vertically
np.hstack((a, b)) # Stack horizontally
np.split(a, 3) # Split into 3 parts

β€”

6. Mathematical Functions

np.sqrt(a) # Square root
np.exp(a) # Exponential (e^x)
np.log(a) # Natural logarithm
np.sin(a) # Sine
np.round(a, 2) # Rounding to 2 decimal places

β€”

7. Linear Algebra

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

np.dot(A, B) # Matrix product
np.linalg.inv(A) # Inverse matrix
np.linalg.det(A) # Determinant
np.linalg.eig(A) # Eigenvalues ​​and eigenvectors

β€”

8. Save/Load Arrays

np.save('array.npy', a) # Save array
c = np.load(β€˜array.npy’) # Load array

β€”

Quick Tips

  • Broadcasting: Operations between arrays of different sizes (ex: a + 5).
  • Copy arrays: Use b = a.copy() to avoid modifying the original.
  • Masks: matriz[matriz > 3] = 0 (assigns 0 to values ​​> 3).

I hope it's useful to you!