[英]Python: 2D Numpy Array (Matrix) - Finding Sum of Negative Numbers (Rows)
我有一個矩陣(使用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行,即使它將有更多行,我也不會對它們感興趣。
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
>>>
遍歷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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.