[英]Assign a value to entire row in numpy array
I have the following example of an array with grades: 我有一个带有成绩的数组的以下示例:
grades = np.array([[ 1, 1, 2, -3],[ 4, 5, 6, 7],[ 8, 9, -3, 11],[12, 13, 14, 15]])
I would like to identify the elements with "-3" and change their entire row to that number, for example the result: 我想用“ -3”标识元素,并将其整个行更改为该数字,例如结果:
grades = np.array([[ -3, -3, -3, -3],[ 4, 5, 6, 7],[ -3, -3, -3, -3],[12, 13, 14, 15]])
So far I tried: 到目前为止,我尝试了:
grades[np.argwhere(grades==-3)]=-3
but i get the following result, where the there are other rows affected as well: 但我得到以下结果,其中还有其他受影响的行:
array([[-3, -3, -3, -3],[ 4, 5, 6, 7],[-3, -3, -3, -3],[-3, -3, -3, -3],[16, 17, 18, 19]])
Any Idea please? 有任何想法吗? Thanks! 谢谢!
First find which of the rows contain a -3 using simple ==
and numpy.any
. 首先使用简单==
和numpy.any
查找哪些行包含-3。 Now index on this boolean array and assign -3 to it, broadcasting will take care of the rest. 现在,在此布尔数组上建立索引并为其分配-3,广播将处理其余的事情。
>>> grades = np.array([[ 1, 1, 2, -3],[ 4, 5, 6, 7],[ 8, 9, -3, 11],[12, 13, 14, 15]])
>>> grades[np.any(grades == -3, axis=1)] = -3
>>> grades
array([[-3, -3, -3, -3],
[ 4, 5, 6, 7],
[-3, -3, -3, -3],
[12, 13, 14, 15]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.