问题:给定大小为3 x 3的矩阵垫,请找出末尾累积总和大于或等于150的每一行中的所有偶数。
我能够找到和,但无法提取按行和,并且在将这些按行偶数和分配给变量时也遇到问题。
所以我的代码看起来不错,但是后来我不知道如何提取偶数的按行和。
import numpy as np
mat = np.array([[51,21,14],
[56,85,22],
[99,666,230]]).reshape(3,3)
mat2=mat[mat%2==0]
res_mat=np.cumsum(mat2[:1])
print(mat2)
print(res_mat)
答案 0 :(得分:0)
如果使用numpy解决您的问题,此答案将无济于事,但是不使用它可能会更容易。
mat = [[51, 21, 14], [56, 85, 22], [99, 666, 230]]
even_numbers_in_target_rows = list()
for row in mat:
if sum(row) >= 150:
for val in row:
if val % 2 == 0:
even_numbers_in_target_rows.append(val)
print(even_numbers_in_target_rows)
步骤:
答案 1 :(得分:0)
如果我正确理解了问题(并且感觉写起来很尴尬),则必须找到总和> = 150的行:
rows = mat[mat.sum(axis=1) >= 150]
然后从中选择偶数:
rows[rows % 2 == 0]
#array([ 56, 22, 666, 230])
答案 2 :(得分:0)
注意:这个问题有点模棱两可,因为不清楚“谁”是指行还是指偶数。 我假设是后者。前者会更容易。
您可以将np.bincount
与np.where
一起使用
# find even numbers
even = mat&1 == 0
# translate mask into coordinates
y, x = np.where(even)
# use y coordinate to group into rows
np.bincount(y, mat[even], mat.shape[0])
# array([ 14., 78., 896.])
答案 3 :(得分:-1)
您可以通过沿每一行取和,然后使用所得的布尔数组将其索引到原始数组中来进行此操作。然后,只需获得偶数:
document-level locking
输出:
mat = np.array([[51, 21, 14],
[56, 85, 22],
[99, 666, 230]])
uniques = np.unique(mat[mat.sum(axis=1) > 150])
uniques[uniques % 2 == 0]