w3resource

NumPy - Cumulative sum of large array using For loop and optimization

NumPy: Performance Optimization Exercise-11 with Solution

Write a NumPy program that creates a function to calculate the cumulative sum of a large NumPy array using a for loop. Optimize it using NumPy's cumsum() function.

Sample Solution:

Python Code:

import numpy as np

# Generate a large 1D NumPy array with random integers
large_array = np.random.randint(1, 1000, size=1000000)

# Function to calculate cumulative sum using a for loop
def cumulative_sum_with_loop(arr):
    cum_sum = np.empty_like(arr)
    cum_sum[0] = arr[0]
    for i in range(1, len(arr)):
        cum_sum[i] = cum_sum[i - 1] + arr[i]
    return cum_sum

# Calculate cumulative sum using the for loop method
cumsum_with_loop = cumulative_sum_with_loop(large_array)

# Calculate cumulative sum using NumPy's cumsum() function
cumsum_with_numpy = np.cumsum(large_array)

# Display first 10 results to verify
print("First 10 results using for loop:")
print(cumsum_with_loop[:10])

print("First 10 results using NumPy:")
print(cumsum_with_numpy[:10])

Output:

First 10 results using for loop:
[ 654 1458 2169 2433 2841 3397 4373 5060 6027 6726]
First 10 results using NumPy:
[ 654 1458 2169 2433 2841 3397 4373 5060 6027 6726]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Generating a large array: A large 1D NumPy array with random integers is generated.
  • Defining the function: A function cumulative_sum_with_loop is defined to calculate the cumulative sum using a for loop.
  • Calculating with loop: The cumulative sum is calculated using the for loop method.
  • Calculating with numpy: The cumulative sum is calculated using NumPy's built-in cumsum() function.
  • Displaying results: The first 10 results from both methods are printed out to verify correctness.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: NumPy - Element-wise division of large arrays using For loop and optimization.
Next: NumPy - Find Indices of Maximum element in large array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/numpy-cumulative-sum-of-large-array-using-for-loop-and-optimization.php