Mathematical & Aggregation

Estimated reading: 2 minutes 18 views

Mathematical Functions

NumPy provides a wide range of mathematical functions that can be applied to arrays:

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

# Square root
sqrt_arr = np.sqrt(arr)

# Exponential
exp_arr = np.exp(arr)

# Trigonometric functions (sin, cos, tan)
sin_arr = np.sin(arr)
cos_arr = np.cos(arr)
tan_arr = np.tan(arr)

Aggregation Functions

NumPy allows you to perform aggregation operations on arrays, such as finding the sum, mean, maximum, and minimum:

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

# Sum of array elements
sum_arr = np.sum(arr)

# Mean of array elements
mean_arr = np.mean(arr)

# Maximum and minimum values
max_value = np.max(arr)
min_value = np.min(arr)

Random Module

The numpy.random module is used to generate random numbers. It’s particularly useful in simulations and statistical applications:

# Generate a random array of shape (3, 3) with values between 0 and 1
random_array = np.random.rand(3, 3)
print(random_array)

Saving and Loading Arrays

You can save and load NumPy arrays to/from files:

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

# Save array to a file
np.save('my_array.npy', arr)

# Load array from a file
loaded_arr = np.load('my_array.npy')
print(loaded_arr)

Linear Algebra

NumPy provides functions for linear algebra operations, including matrix multiplication, eigenvalues, and solving linear systems:

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

# Matrix multiplication
result_matrix = np.dot(matrix_a, matrix_b)
print(result_matrix)

Broadcasting

NumPy allows operations between arrays of different shapes and sizes through broadcasting:

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

# Broadcasting scalar to the array
result = arr * scalar
print(result)

NumPy Documentation

For in-depth exploration and reference, always consult the official NumPy documentation. It provides detailed information about functions, modules, and advanced features.

These concepts should provide a solid foundation for your journey into NumPy. Happy coding!

Share this Doc

Mathematical & Aggregation

Or copy link