Reputation: 27
I have a matrix (using numpy
), user enters number of rows and columns. After going through some FOR loops, user enters elements, of course depending on what number of rows and columns did he/she has chosen.
Now I need to find a sum of negative elements for every row below row 7 and output this every row sum, right after the exact row. Here is my code (even though code for this last thing doesn't work)
import numpy as np
A = list()
n = int(input("How many rows: "))
m = int(input("How many columns: "))
for x in range(n):
if n <= 0 or n>10:
print("Out of range")
break
elif m <= 0 or m>10:
print("Out of range")
break
else:
for y in range(m):
num = input("Element: ")
A.append(int(num))
shape = np.reshape(A,(n,m))
for e in range(n < 7):
if e < 0:
print(sum(e))
print(shape)
If as a user, I will enter 3 rows and 3 columns, I can get something like this (I'll enter some numbers to explain what I need):
[-1, 2, -3]
[-4, 5, -6]
[-7, -8, 9]
I should get something like this:
[-1, 2, -3] Sum of Negative Elements In This Row (Till 7th) [-4]
[-4, 5, -6] Sum of Negative Elements In This Row (Till 7th) [-10]
[-7, -8, 9] Sum of Negative Elements In This Row (Till 7th) [-15]
Also please don't forget I need it only till row 7, even if it will have more rows, I am not interested in them.
Upvotes: 0
Views: 1196
Reputation: 23753
a = np.random.random_integers(-1, 1, (10,3))
>>> a
array([[ 0, 0, -1],
[ 1, -1, -1],
[ 0, 1, 1],
[-1, 0, 0],
[ 1, -1, 0],
[-1, 1, 1],
[ 0, 1, 0],
[ 1, -1, 0],
[-1, 0, 1],
[ 1, -1, 1]])
>>>
You can slice a numpy array in any of its dimensions. The first seven rows would be:
>>> a[:7,:]
array([[ 0, 0, -1],
[ 1, -1, -1],
[ 0, 1, 1],
[-1, 0, 0],
[ 1, -1, 0],
[-1, 1, 1],
[ 0, 1, 0]])
>>>
Iterating over the array produces rows which can be summed. Boolean indexing can be used to select items based on a condition:
>>> for row in a[:7,:]:
... less_than_zero = row[row < 0]
... sum_less_than = np.sum(less_than_zero)
... print('row:{:<14}\tless than zero:{:<11}\tsum:{}'.format(row, less_than_zero, sum_less_than))
row:[ 0 0 -1] less than zero:[-1] sum:-1
row:[ 1 -1 -1] less than zero:[-1 -1] sum:-2
row:[0 1 1] less than zero:[] sum:0
row:[-1 0 0] less than zero:[-1] sum:-1
row:[ 1 -1 0] less than zero:[-1] sum:-1
row:[-1 1 1] less than zero:[-1] sum:-1
row:[0 1 0] less than zero:[] sum:0
>>>
Upvotes: 1
Reputation: 10096
Go through every row of your 2D array and select the negative values with row[row < 0]
and calculate the sum of these values:
import numpy as np
a = np.array([[-1, 2, -3], [-4, 5, -6], [-7, -8, 9]]) # your array
for row in a:
neg_sum = sum(row[row < 0]) # sum of negative values
print('{} Sum of Negative Elements In This Row: {}'.format(row, neg_sum))
This prints:
[-1 2 -3] Sum of Negative Elements In This Row: -4
[-4 5 -6] Sum of Negative Elements In This Row: -10
[-7 -8 9] Sum of Negative Elements In This Row: -15
Upvotes: 0