NumPy is a powerful Python library for numerical computations, and it provides a wide range of functions for various operations, including summing arrays. Let's go through some step-by-step examples of how to use the numpy.sum() function:
Summing a 1D Array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
result = np.sum(arr)
print(result)
In this example, we import NumPy, create a 1D array, and use np.sum() to calculate the sum of all elements in the array. The result will be 15.
Summing a 2D Array (Matrix):
import numpy as np
matrix = np.array([[101, 102, 103], [104, 105, 106], [107, 108, 109]])
result = np.sum(matrix)
print(result)
945
Here, we create a 2D array (matrix) and calculate the sum of all elements. The result will be 45.
Read also:
- Python Flask Tutorial setting up a Flask and SQL Database Connection
- Python Flask Student List CRUD system
- How to create a Python Flask with mysql Database
Summing Along a Specific Axis:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9])
# Sum along rows (axis 0)
row_sum = np.sum(matrix, axis=0)
# Sum along columns (axis 1)
col_sum = np.sum(matrix, axis=1)
print("Row Sum:")
print(row_sum)
print("Column Sum:")
print(col_sum)
Row Sum:
[12 15 18]
Column Sum:
[ 6 15 24]
In this example, we create a matrix and calculate the sum along different axes. axis=0 sums along rows, and axis=1 sums along columns.
Summing a Subset of Elements:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
subset_sum = np.sum(arr[1:4]) # Sum elements from index 1 to 3
print(subset_sum)
9
Here, we calculate the sum of a subset of elements in a 1D array.
Ignoring NaN Values:
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
arr = np.array([1.0, 2.0, np.nan, 4.0, 5.0])
result = np.nansum(arr)
print(result)
You can use np.nansum() to calculate the sum of elements while ignoring NaN values.
Cumulative Sum:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
cumulative_sum = np.cumsum(arr)
print(cumulative_sum)
[ 1 3 6 10 15]
To calculate the cumulative sum of an array, you can use np.cumsum().
These are some step-by-step examples of using the numpy.sum() function in various scenarios. NumPy is a versatile library, and you can adapt these examples to suit your specific needs.
These are some step-by-step examples of using the numpy.sum() function in various scenarios. NumPy is a versatile library, and you can adapt these examples to suit your specific needs.