我有一个矩阵(使用numpy
),用户输入行数和列数。经过一些FOR循环后,用户输入元素,当然取决于他/她选择的行数和列数。
现在我需要为第7行下面的每一行找到一个负数元素的总和,然后在确切的行之后输出每一行的总和。这是我的代码(尽管最后一件事的代码不起作用)
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)
如果作为用户,我将输入3行3列,我可以得到这样的东西(我会输入一些数字来解释我需要的东西):
[-1, 2, -3]
[-4, 5, -6]
[-7, -8, 9]
我应该得到这样的东西:
[-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]
另外请不要忘记我只需要排第7行,即使它有更多行,我对它们也不感兴趣。
答案 0 :(得分:1)
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]])
>>>
您可以在任何维度中切割numpy数组。前七行是:
>>> a[:7,:]
array([[ 0, 0, -1],
[ 1, -1, -1],
[ 0, 1, 1],
[-1, 0, 0],
[ 1, -1, 0],
[-1, 1, 1],
[ 0, 1, 0]])
>>>
迭代数组会产生可以求和的行。布尔索引可用于根据条件选择项目:
>>> 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
>>>
答案 1 :(得分:0)
浏览2D数组的每一行并使用row[row < 0]
选择负值并计算这些值的总和:
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))
打印:
[-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