Using ndarray.sum() method in NumPy (6 examples)

Updated: February 27, 2024 By: Guest Contributor Post a comment

Introduction

This tutorial covers the ndarray.sum() method in NumPy, showcasing its versatility through six progressively complex examples. Whether you’re new to NumPy or looking to deepen your understanding, this guide provides valuable insights into one of the library’s foundational methods.

A Brief Overview of ndarray.sum()

The ndarray.sum() method is a powerful feature of the NumPy library that allows for the efficient summation of elements across arrays. NumPy is a foundation for scientific computing in Python, offering a rich ecosystem for handling multi-dimensional data structures known as arrays. The .sum() method simplifies adding array elements, reducing them to their aggregate sum.

Syntax:

numpy.ndarray.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)

Parameters:

  • axis: (Optional) Axis or axes along which the sum is performed. If not specified, the sum is computed over all elements of the array.
  • dtype: (Optional) Data type of the returned array and of the accumulator in which the elements are summed. If not specified, the data type of the array is used.
  • out: (Optional) Output array where the result is placed.
  • keepdims: (Optional) If True, the reduced dimensions are retained with a length of 1. Default is False.
  • initial: (Optional) Starting value for the sum.
  • where: (Optional) Array-like or boolean expression. If provided, only the elements where condition is True are summed.

Basic Usage

import numpy as np

# Creating a simple array
arr = np.array([1, 2, 3, 4, 5])
# Summing array elements
sum_result = arr.sum()
print('Sum of array:', sum_result)

Output:

Sum of array: 15

Summing Along an Axis

import numpy as np

# Creating a 2D array
arr_2d = np.array([[1, 2], [3, 4]])
# Summing elements along the 0th axis (column-wise)
sum_col = arr_2d.sum(axis=0)
print('Column-wise sum:', sum_col)

# Summing elements along the 1st axis (row-wise)
sum_row = arr_2d.sum(axis=1)
print('Row-wise sum:', sum_row)

Output:

Column-wise sum: [4 6]
Row-wise sum: [3 7]

Computing the Cumulative Sum

import numpy as np

# Creating an array
arr = np.array([1, 2, 3, 4, 5])
# Computing the cumulative sum
cum_sum = arr.cumsum()
print('Cumulative Sum:', cum_sum)

Output:

Cumulative Sum: [ 1, 3, 6, 10, 15]

Using sum() with Boolean Arrays

import numpy as np

# Creating a boolean array
bool_arr = np.array([True, False, True, True, False])
# Summing the boolean array (True=1, False=0)
bool_sum = bool_arr.sum()
print('Boolean array sum:', bool_sum)

Output:

Boolean array sum: 3

Handling Multidimensional Arrays

import numpy as np

# Creating a 3D array
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Sum across all dimensions
overall_sum = arr_3d.sum()
print('Overall sum:', overall_sum)

# Summing over the first axis (sums matrices together)
first_axis_sum = arr_3d.sum(axis=0)
print('First axis sum:', first_axis_sum)

Output:

Overall sum: 36
First axis sum: [[ 6, 8],
[10, 12]]

Weighted Sum Using multiply() and sum()

import numpy as np

# Creating arrays for weights and values
weights = np.array([0.2, 0.3, 0.5])
values = np.array([10, 20, 30])
# Computing the weighted sum
weighted_sum = np.multiply(weights, values).sum()
print('Weighted sum:', weighted_sum)

Output:

Weighted sum: 23.0

Conclusion

Through these examples, we’ve seen how ndarray.sum() facilitates various types of summations in NumPy, from simple arrays to multidimensional and weighted sums. This method is fundamental, yet powerful, enabling efficient and concise data aggregation. Mastery of ndarray.sum() is a stepping stone to leveraging the full potential of NumPy for data analysis and scientific computing.