Python:2D Numpy数组(矩阵)-查找负数(行)之和
我有一个矩阵(使用Python:2D Numpy数组(矩阵)-查找负数(行)之和,python,arrays,numpy,matrix,Python,Arrays,Numpy,Matrix,我有一个矩阵(使用numpy),用户输入行数和列数。经过一些FOR循环后,用户输入元素,当然这取决于他/她选择的行数和列数 现在我需要为第7行下面的每一行找到一个负元素的和,并在精确的行之后输出这个每一行的和。这是我的代码(即使最后一件事的代码不起作用) 我应该得到这样的东西: [-1, 2, -3] Sum of Negative Elements In This Row (Till 7th) [-4] [-4, 5, -6] Sum of Negative Elements In This
numpy
),用户输入行数和列数。经过一些FOR循环后,用户输入元素,当然这取决于他/她选择的行数和列数
现在我需要为第7行下面的每一行找到一个负元素的和,并在精确的行之后输出这个每一行的和。这是我的代码(即使最后一件事的代码不起作用)
我应该得到这样的东西:
[-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行,即使它会有更多的行,我对他们不感兴趣
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
>>>
[:7,:]中的行的>:
... 小于零=行[行<0]
... 和小于等于np.和(小于零)
... print('row:{:遍历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))
非常感谢,这正是我所需要的。有一个问题,如果我在a中的行中添加[:7,:]即使矩阵是8x8,它也会减少所有内容,我如何能够显示整个矩阵,但计算负数直到第7行?保留整行(,用于a中的行),但将其包含在负和=…
行中。因此我需要添加[:7,:]不是到(对于a中的行),而是到(neg_sum=line
)?我真的不知道在哪里添加,它给了我一个错误,维度是8,我一直到7,但没有结果
>>> 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
>>>
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