Numpy Array Sum
Numpy is a fundamental package for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. One of the most common operations that can be performed with numpy arrays is summing their elements. This article will explore various ways to sum elements in a numpy array, including summing all elements, summing along an axis, and using other related functions.
1. Summing All Elements in an Array
To sum all elements in a numpy array, you can use the np.sum()
function. This function returns the sum of array elements over a given axis.
Example 1: Basic Sum of All Elements
import numpy as np
array = np.array([1, 2, 3, 4, 5])
result = np.sum(array)
print(result) # Output: 15
Output:
Example 2: Sum of a 2D Array
import numpy as np
array = np.array([[1, 2], [3, 4]])
result = np.sum(array)
print(result) # Output: 10
Output:
2. Summing Elements Along an Axis
Numpy allows you to specify the axis along which the sum should be computed. The axes are defined for arrays with more than one dimension. A 2-dimensional array has two axes: axis 0 runs downward down the rows, and axis 1 runs horizontally across the columns.
Example 3: Summing Each Column
import numpy as np
array = np.array([[1, 2], [3, 4]])
column_sum = np.sum(array, axis=0)
print(column_sum) # Output: [4 6]
Output:
Example 4: Summing Each Row
import numpy as np
array = np.array([[1, 2], [3, 4]])
row_sum = np.sum(array, axis=1)
print(row_sum) # Output: [3 7]
Output:
3. Using np.add.reduce
Numpy also provides a method called reduce
on ufuncs (universal functions). For addition, you can use np.add.reduce
which is similar to np.sum
but slightly lower level.
Example 5: Reduce Sum on 1D Array
import numpy as np
array = np.array([1, 2, 3, 4, 5])
result = np.add.reduce(array)
print(result) # Output: 15
Output:
Example 6: Reduce Sum on 2D Array Along an Axis
import numpy as np
array = np.array([[1, 2], [3, 4]])
result = np.add.reduce(array, axis=1)
print(result) # Output: [3 7]
Output:
4. Cumulative Sum with np.cumsum
The cumulative sum is a sequence of partial sums of a given sequence. You can calculate it in numpy using the np.cumsum
function.
Example 7: Cumulative Sum of a 1D Array
import numpy as np
array = np.array([1, 2, 3, 4, 5])
cumulative_sum = np.cumsum(array)
print(cumulative_sum) # Output: [ 1 3 6 10 15]
Output:
Example 8: Cumulative Sum of a 2D Array Along an Axis
import numpy as np
array = np.array([[1, 2], [3, 4]])
cumulative_sum = np.cumsum(array, axis=0)
print(cumulative_sum) # Output: [[1 2] [4 6]]
Output:
5. Sum with Initial Value Using np.sum
You can also specify an initial value to start the sum with, using the initial
parameter in the np.sum
function.
Example 9: Sum with Initial Value
import numpy as np
array = np.array([1, 2, 3, 4, 5])
result = np.sum(array, initial=10)
print(result) # Output: 25
Output:
Example 10: Sum of 2D Array with Initial Value
import numpy as np
array = np.array([[1, 2], [3, 4]])
result = np.sum(array, initial=5)
print(result) # Output: 15
Output:
6. Weighted Sum Using np.dot
For computing the weighted sum of array elements, you can use the np.dot
function, which performs a dot product of two arrays.
Example 11: Weighted Sum of 1D Arrays
import numpy as np
array = np.array([1, 2, 3, 4, 5])
weights = np.array([0.1, 0.2, 0.3, 0.4, 0.5])
weighted_sum = np.dot(array, weights)
print(weighted_sum) # Output: 5.5
Output:
Example 12: Weighted Sum of 2D Array
import numpy as np
array = np.array([[1, 2], [3, 4]])
weights = np.array([0.5, 0.5])
weighted_sum = np.dot(array, weights)
print(weighted_sum) # Output: [1.5 3.5]
Output:
7. Sum Over Multiple Axes
Numpy allows you to sum over multiple axes at once by passing a tuple of axes to the axis
parameter.
Example 13: Sum Over Multiple Axes
import numpy as np
array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
result = np.sum(array, axis=(0, 1))
print(result) # Output: [16 20]
Output:
Example 14: Sum Over All Axes
import numpy as np
array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
result = np.sum(array, axis=(0, 1, 2))
print(result) # Output: 36
Output:
8. Checking for NaN Values in Sum
When dealing with real-world data, you might encounter NaN (Not a Number) values. Numpy provides a function np.nansum
which ignores these NaN values during summation.
Example 15: Sum with NaN Values
import numpy as np
array = np.array([1, np.nan, 3, 4, 5])
result = np.nansum(array)
print(result) # Output: 13
Output:
Example 16: Sum of 2D Array Ignoring NaN
import numpy as np
array = np.array([[1, np.nan], [3, 4]])
result = np.nansum(array)
print(result) # Output: 8
Output:
9. Sum with Conditions Using np.where
You can perform conditional summation using np.where
. This function allows you to specify conditions under which elements should be summed.
Example 17: Conditional Sum
import numpy as np
array = np.array([1, 2, 3, 4, 5])
condition = array > 3
result = np.sum(np.where(condition, array, 0))
print(result) # Output: 9
Output:
Example 18: Conditional Sum in 2D Array
import numpy as np
array = np.array([[1, 2], [3, 4]])
condition = array > 2
result = np.sum(np.where(condition, array, 0))
print(result) # Output: 7
Output:
10. Summing with External Libraries
While numpy provides comprehensive tools for array summation, sometimes you might want to use external libraries for specific purposes, such as pandas
for data frames or scipy
for scientific computing.
Example 19: Summing with Pandas
import numpy as np
import pandas as pd
array = np.array([1, 2, 3, 4, 5])
series = pd.Series(array)
result = series.sum()
print(result) # Output: 15
Output:
Example 20: Summing with Scipy
import numpy as np
from scipy import stats
array = np.array([1, 2, 3, 4, 5])
result = stats.tmean(array)
print(result) # Output: 3.0
Output:
In conclusion, numpy provides a wide range of options for summing elements in an array. Whether you need to sum all elements, sum along an axis, compute a weighted sum, or handle NaN values, numpy has a function that can help. By understanding these functions and how to use them, you can perform array summation tasks more effectively in your Python programs.