我有以下带有成绩的数组示例:
grades = np.array([[ 1, 1, 2, -3],[ 4, 5, 6, 7],[ 8, 9, -3, 11],[12, 13, 14, 15]])
我想用“-3”标识元素并将其整行更改为该数字,例如结果:
grades = np.array([[ -3, -3, -3, -3],[ 4, 5, 6, 7],[ -3, -3, -3, -3],[12, 13, 14, 15]])
到目前为止我尝试过:
grades[np.argwhere(grades==-3)]=-3
但我得到以下结果,其中还有其他行受到影响:
array([[-3, -3, -3, -3],[ 4, 5, 6, 7],[-3, -3, -3, -3],[-3, -3, -3, -3],[16, 17, 18, 19]])
请问有什么想法吗?谢谢!
最佳答案
首先使用简单的 ==
和 numpy.any
查找哪一行包含 -3。现在索引这个 bool 数组并为其分配 -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]])
关于python - 为 numpy 数组中的整行赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33811576/