Python NumPy Tips
CodeProgrammerPython tip:
Create a NumPy array from a Python list.
import numpy as np
a = np.array([1, 2, 3])Python tip:
Create a multi-dimensional array.
import numpy as np
b = np.array([[1, 2, 3], [4, 5, 6]])Python tip:
Create an array of zeros with a specific shape.
import numpy as np
zeros_array = np.zeros((3, 4))Python tip:
Create an array of ones.
import numpy as np
ones_array = np.ones((2, 5))Python tip:
Create an array with a range of elements.
import numpy as np
range_array = np.arange(10, 20, 2)Python tip:
Create an array with a specific number of elements, evenly spaced.
import numpy as np
linspace_array = np.linspace(0, 1, 5)Python tip:
Create an array filled with a specific value.
import numpy as np
full_array = np.full((2, 3), 7)Python tip:
Create an identity matrix.
import numpy as np
identity_matrix = np.eye(3)Python tip:
Create an array with random values from a uniform distribution [0, 1).
import numpy as np
random_array = np.random.rand(3, 3)Python tip:
Create an array with random values from a standard normal distribution.
import numpy as np
random_normal_array = np.random.randn(2, 4)Python tip:
Create an array of random integers within a range.
import numpy as np
random_integers = np.random.randint(0, 100, size=(5,))Python tip:
Get the shape of an array.
import numpy as np
a = np.array([[1, 2], [3, 4], [5, 6]])
print(a.shape)Python tip:
Get the data type of an array's elements.
import numpy as np
a = np.array([1, 2, 3])
print(a.dtype)Python tip:
Specify the data type during array creation.
import numpy as np
a = np.array([1.1, 2.2, 3.3], dtype=np.int32)Python tip:
Get the number of dimensions of an array.
import numpy as np
a = np.zeros((5, 5, 5))
print(a.ndim)Python tip:
Get the total number of elements in an array.
import numpy as np
a = np.ones((10, 10))
print(a.size)Python tip:
Reshape an array to a different, compatible shape.
import numpy as np
a = np.arange(12)
b = a.reshape(3, 4)Python tip:
Access an element in a 1D array.
import numpy as np
a = np.array([10, 20, 30, 40])
element = a[2]Python tip:
Access an element in a 2D array.
import numpy as np
a = np.array([[1, 2], [3, 4]])
element = a[1, 0] # Accesses 3Python tip:
Slice a 1D array.
import numpy as np
a = np.arange(10)
slice_a = a[2:5] # Elements at index 2, 3, 4Python tip:
Slice a 2D array to get a row.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
first_row = a[0, :]Python tip:
Slice a 2D array to get a column.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
second_col = a[:, 1]Python tip:
Use boolean indexing to filter an array.
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
greater_than_3 = a[a > 3]Python tip:
Use fancy indexing with a list of indices.
import numpy as np
a = np.arange(10, 20)
elements = a[[0, 2, 8]]Python tip:
Slicing an array creates a view, not a copy. Modifying the view changes the original.
import numpy as np
a = np.arange(5)
b = a[2:4]
b[0] = 99 # This changes 'a' as wellPython tip:
Use .copy() to create a new array with its own data.
import numpy as np
a = np.arange(5)
b = a[2:4].copy()
b[0] = 99 # This does NOT change 'a'Python tip:
Perform element-wise addition between two arrays.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a + bPython tip:
Perform element-wise multiplication.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a * bPython tip:
Broadcasting allows operations on arrays of different shapes.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = a + 100 # Scalar is broadcast to the shape of 'a'Python tip:
A more complex broadcasting example.
import numpy as np
a = np.ones((3, 3))
b = np.arange(3)
c = a + b # b is broadcast to (3, 3)Python tip:
Use universal functions (ufuncs) like np.sqrt.
import numpy as np
a = np.array([4, 9, 16])
b = np.sqrt(a)Python tip:
Calculate the sum of all elements in an array.
import numpy as np
a = np.array([[1, 2], [3, 4]])
total_sum = a.sum()Python tip:
Calculate the sum along a specific axis (e.g., columns).
import numpy as np
a = np.array([[1, 2], [3, 4]])
col_sums = a.sum(axis=0)Python tip:
Calculate the sum along rows.
import numpy as np
a = np.array([[1, 2], [3, 4]])
row_sums = a.sum(axis=1)Python tip:
Find the minimum and maximum value in an array.
import numpy as np
a = np.array([5, 1, 9, 3])
min_val = a.min()
max_val = a.max()Python tip:
Calculate the mean of an array.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
mean_val = a.mean()Python tip:
Calculate the standard deviation.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
std_dev = a.std()Python tip:
Find the index of the maximum value.
import numpy as np
a = np.array([10, 50, 20])
max_index = a.argmax()Python tip:
Find the index of the minimum value.
import numpy as np
a = np.array([10, 5, 20])
min_index = a.argmin()Python tip:
Use the @ operator for matrix multiplication.
import numpy as np
a = np.ones((2, 3))
b = np.full((3, 2), 2)
c = a @ bPython tip:
Get the transpose of an array.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
a_t = a.TPython tip:
Calculate the inverse of a matrix.
import numpy as np
a = np.array([[1, 2], [3, 4]])
inv_a = np.linalg.inv(a)Python tip:
Calculate the determinant of a matrix.
import numpy as np
a = np.array([[1, 2], [3, 4]])
det_a = np.linalg.det(a)Python tip:
Solve a system of linear equations.
import numpy as np
A = np.array([[2, 1], [1, 3]])
b = np.array([1, 2])
x = np.linalg.solve(A, b)Python tip:
Flatten a multi-dimensional array into 1D.
import numpy as np
a = np.array([[1, 2], [3, 4]])
flat_a = a.flatten() # Returns a copyPython tip:
Use ravel to flatten an array, which may return a view.
import numpy as np
a = np.array([[1, 2], [3, 4]])
ravel_a = a.ravel() # Often faster, might return a viewPython tip:
Concatenate arrays along an axis.
import numpy as np
a = np.array([1, 2])
b = np.array([3, 4])
c = np.concatenate((a, b))Python tip:
Stack arrays vertically (row-wise).
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
v_stack = np.vstack((a, b))Python tip:
Stack arrays horizontally (column-wise).
import numpy as np
a = np.array([[1], [2]])
b = np.array([[3], [4]])
h_stack = np.hstack((a, b))Python tip:
Split an array into multiple sub-arrays.
import numpy as np
a = np.arange(9)
sub_arrays = np.split(a, 3)Python tip:
Use np.where as a vectorized ternary operator.
import numpy as np
a = np.arange(10)
b = np.where(a < 5, a, 10*a)Python tip:
Sort an array.
import numpy as np
a = np.array([3, 1, 4, 1, 5, 9])
sorted_a = np.sort(a)Python tip:
Get the indices that would sort an array.
import numpy as np
a = np.array([3, 1, 4])
sort_indices = np.argsort(a)Python tip:
Find the unique elements in an array.
import numpy as np
a = np.array([1, 2, 2, 3, 3, 3, 4])
unique_elements = np.unique(a)Python tip:
Set a seed for random number generation for reproducibility.
import numpy as np
np.random.seed(42)
random_val = np.random.rand()Python tip:
Perform in-place operations to save memory.
import numpy as np
a = np.ones(1000000)
b = np.ones(1000000)
a += b # Modifies 'a' directly without creating a new arrayPython tip:
Clip values in an array to be within a specified range.
import numpy as np
a = np.arange(10)
clipped_a = np.clip(a, 2, 7)Python tip:
Calculate the cumulative sum of elements.
import numpy as np
a = np.array([1, 2, 3, 4])
cum_sum = np.cumsum(a)Python tip:
Calculate the dot product of two 1D arrays.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
dot_product = np.dot(a, b)Python tip:
Check if any element in a boolean array is True.
import numpy as np
a = np.array([False, False, True])
result = np.any(a)Python tip:
Check if all elements in a boolean array are True.
import numpy as np
a = np.array([True, False, True])
result = np.all(a)Python tip:
Compare two arrays element-wise.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, 5, 3])
comparison = (a == b)Python tip:
Count non-zero elements in an array.
import numpy as np
a = np.array([1, 0, 5, 0, 0, 9])
count = np.count_nonzero(a)Python tip:
Repeat elements of an array.
import numpy as as np
a = np.array([1, 2, 3])
repeated_a = np.repeat(a, 3)Python tip:
Tile an array to construct a larger array.
import numpy as np
a = np.array([1, 2])
tiled_a = np.tile(a, (3, 2))Python tip:
Save a NumPy array to a binary file (.npy).
import numpy as np
a = np.arange(10)
np.save('my_array.npy', a)Python tip:
Load a NumPy array from a .npy file.
import numpy as np
loaded_a = np.load('my_array.npy')Python tip:
Save an array to a text file.
import numpy as np
a = np.array([[1, 2], [3, 4]])
np.savetxt('my_array.txt', a, delimiter=',')Python tip:
Load data from a text file.
import numpy as np
loaded_a = np.loadtxt('my_array.txt', delimiter=',')Python tip:
Use np.einsum for complex operations like tensor contractions.
import numpy as np
a = np.arange(25).reshape(5,5)
trace = np.einsum('ii', a)Python tip:
Create a meshgrid for evaluating functions on a grid.
import numpy as np
x = np.linspace(-5, 5, 10)
y = np.linspace(-5, 5, 10)
xx, yy = np.meshgrid(x, y)Python tip:
Find the difference between adjacent elements in an array.
import numpy as np
a = np.array([1, 3, 8, 20])
diff_a = np.diff(a)Python tip:
Perform set operations like intersection on 1D arrays.
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
intersection = np.intersect1d(a, b)Python tip:
Perform the union of two 1D arrays.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([3, 4, 5])
union = np.union1d(a, b)Python tip:
Find elements in one array that are not in another.
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
set_diff = np.setdiff1d(a, b)Python tip:
Create a view of an array with a different data type.
import numpy as np
a = np.array([1, 2, 3], dtype=np.int32)
b = a.view(np.uint32)Python tip:
Round array elements to the nearest integer.
import numpy as np
a = np.array([1.2, 2.8, 3.5])
rounded_a = np.round(a)Python tip:
Vectorize a Python function to apply it to arrays.
import numpy as np
def my_func(x):
return x * 2 if x > 5 else x / 2
vectorized_func = np.vectorize(my_func)
result = vectorized_func(np.arange(10))Python tip:
Create a histogram from data.
import numpy as np
data = np.random.randn(1000)
hist, bin_edges = np.histogram(data, bins=10)Python tip:
Calculate outer product of two vectors.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5])
outer_prod = np.outer(a, b)Python tip:
Calculate eigenvalues and eigenvectors of a matrix.
import numpy as np
matrix = np.diag((1, 2, 3))
eigenvalues, eigenvectors = np.linalg.eig(matrix)Python tip:
Use np.nan to represent missing data.
import numpy as np
a = np.array([1, 2, np.nan, 4])Python tip:
Use nan-safe functions for calculations involving missing data.
import numpy as np
a = np.array([1, 2, np.nan, 4])
nan_sum = np.nansum(a)Python tip:
Check for NaN values in an array.
import numpy as np
a = np.array([1, np.nan, 3])
is_nan = np.isnan(a)Python tip:
Choose a random sample from an array.
import numpy as np
a = np.arange(20)
sample = np.random.choice(a, size=5, replace=False)Python tip:
Shuffle an array in-place.
import numpy as np
a = np.arange(10)
np.random.shuffle(a)Python tip:
Fit a polynomial to data points.
import numpy as np
x = np.array([0, 1, 2, 3])
y = np.array([-1, 0.2, 0.9, 2.1])
coefficients = np.polyfit(x, y, 2) # Fit a 2nd degree polynomialPython tip:
Evaluate a polynomial at specific points.
import numpy as np
coefficients = [3, 2, 1] # Represents 3x^2 + 2x + 1
value = np.polyval(coefficients, 2) # Evaluate at x=2Python tip:
Use
np.newaxis to increase the dimension of an array.import numpy as np
a = np.array([1, 2, 3])
row_vector = a[np.newaxis, :]
col_vector = a[:, np.newaxis]Python tip:
Get diagonal elements of a 2D array.
import numpy as np
a = np.arange(9).reshape(3,3)
diag_a = np.diag(a)Python tip:
Create a 2D array from a diagonal.
import numpy as np
a = np.diag([1, 2, 3])Python tip:
Use
np.allclose to compare floating point arrays for approximate equality.import numpy as np
a = np.array([0.1 + 0.2])
b = np.array([0.3])
is_close = np.allclose(a, b)Python tip:
Access memory layout information with flags.
import numpy as np
a = np.array([[1,2], [3,4]], order='C') # C-style (row-major)
print(a.flags)Python tip:
Flip an array vertically (up/down).
import numpy as np
a = np.array([[1, 2], [3, 4]])
flipped_a = np.flipud(a)Python tip:
Flip an array horizontally (left/right).
import numpy as np
a = np.arange(4).reshape(2,2)
flipped_a = np.fliplr(a)#NumPy #Python #DataScience #MachineLearning #ScientificComputing #Vectorization #PythonTips #Programming #Coding #ArrayProgramming