0

How can I add up all the elements of each row of a multidimensional numpy array. I am trying to turn the '--' elements to 0 and then adding all the rows right after. How could I do such a thing? The -- elements of the result of the masked array.

Array = np.array([[--, --, --, --, --, --, --]
 [3, 4, --, --, --, --, --]
 [--, --, 5, 7, 8, 10, --]
 [--, --, --, --, --, --, --]
 [--, --, --, --, --, --, 20]])
np.where(Array != "--", result, 0)
Array.sum(axis=0)

Expected Output:

[0 7 30 0 20]
5
  • Are the --s supposed to be surrounded with quotes? "--" Commented Mar 11, 2021 at 21:22
  • It was actually after formatting an array it gives out -- for the empty spaces in the Array. Commented Mar 11, 2021 at 21:27
  • Array = np.array([[--, --, --, --, --, --, --] [3, 4, --, --, --, --, --] [--, --, 5, 7, 8, 10, --] [--, --, --, --, --, --, --] [--, --, --, --, --, --, 20]]) should throw an error. Commented Mar 11, 2021 at 21:28
  • Is this a masked array or a mixed of string and numbers array (which is an object array)? It would help if you provide how you get this array. Thank you Commented Mar 11, 2021 at 21:29
  • @QWERTYL ye like Ehsan said said it is a masked array Commented Mar 11, 2021 at 21:30

2 Answers 2

3
import numpy as np

array = np.ma.array(
    [
        [0, 0, 0, 0, 0, 0, 0],
        [3, 4, 0, 0, 0, 0, 0],
        [0, 0, 5, 7, 8, 10, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 20]
    ],
    mask=[
        [1, 1, 1, 1, 1, 1, 1],
        [0, 0, 1, 1, 1, 1, 1],
        [1, 1, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 0]
    ]
)

array = array.filled(0)
print(np.sum(array, axis=1))

Alternatively, if you want to apply the sum on the masked array before filling with zeros:

array.fill_value = 0
print(np.ma.sum(array, axis=1).filled(0))
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this

>>> np.where(arr == '--', 0, arr).astype(int).sum(1)
array([ 0,  7, 30,  0, 20])

1 Comment

This does not work since the -- elements are that of a masked array, sorry updated the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.