Member-only story

NumPy is a powerful library for numerical operations in Python. There are many tricks and features in NumPy that can help you write more efficient and concise code that might not be immediately obvious to someone who is new to the library.. Here are some NumPy tricks:
1. Vectorization:
Take advantage of NumPy’s ability to perform element-wise operations on entire arrays without explicit looping. This often leads to faster and more concise code.
# Without vectorization
result = []
for x in array1:
for y in array2:
result.append(x + y)
# With vectorization
result = array1 + array2
2. Broadcasting:
NumPy automatically broadcasts operations on arrays of different shapes, making it easier to work with arrays of different sizes.
# Broadcasting
a = np.array([1.0, 2.0, 3.0])
b = 2.0
result = a * b # [2.0, 4.0, 6.0]
3. Array Slicing and Indexing:
Use array slicing and indexing for efficient access to parts of arrays.
# Slicing
sub_array = array[1:4]
# Indexing
element = array[2]
4. Boolean Indexing:
Use boolean arrays to index into other arrays.
# Boolean indexing
mask = array > 0
positive_values = array[mask]
5. Aggregation Functions:
NumPy provides built-in functions for common aggregations.
# Aggregation
mean_value = np.mean(array)
max_value = np.max(array)
6. Reshaping Arrays:
Use reshape
to change the shape of an array.
# Reshaping
new_shape_array = array.reshape((2, 3))
7. Concatenation and Splitting:
Combine arrays using concatenate
and split them using split
.
# Concatenation
concatenated_array = np.concatenate([array1, array2])
# Splitting
arrays = np.split(array, 3)