w3resource

Advanced NumPy Exercises - Find the sum of a 4x4 array containing random values

NumPy: Advanced Exercise-3 with Solution

Write a NumPy program to create a 4x4 array with random values and find the sum of each row.

Using NumPy, you can create a 4x4 array filled with random values by utilizing the numpy.random.rand function, which generates random numbers in the range [0, 1). To find the sum of each row, you can use the numpy.sum function with the axis parameter set to 1, specifying that the summation should be performed along the rows. This approach provides a straightforward way to handle array operations and computations.

Sample Solution:

Python Code:

import numpy as np
# create a 4x4 array with random values
arr = np.random.rand(4, 4)
# find the sum of each row
row_sum = np.sum(arr, axis=1)
print("Original array:")
print(arr)
print("\nSum of each row:")
print(row_sum)

Output:

Original array:
[[0.97150665 0.4384906  0.52444497 0.45505872]
 [0.98733409 0.3498058  0.44414235 0.08707591]
 [0.86342298 0.68227614 0.02548033 0.83086213]
 [0.7784747  0.3086618  0.49636261 0.70016215]]

Sum of each row:
[2.38950093 1.86835815 2.40204158 2.28366126]

Explanation:

In the above exercise -

arr = np.random.rand(4, 4): This line creates a 4x4 NumPy array arr with random values between 0 and 1 using the rand method from numpy.random module.

row_sum = np.sum(arr, axis=1): This line calculates the sum of each row in the arr numpy array using the sum method from NumPy. The axis parameter is set to 1, which means that the sum is calculated across each row. The resulting array row_sum is a 1-dimensional array with 4 elements, where each element corresponds to the sum of a row in the original arr array.

Python-Numpy Code Editor:

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

Previous: Stack a 3x3 identity matrix vertically and horizontally.
Next: Subtract the mean of each row from each element of a 3x3 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/advanced-numpy-exercise-3.php