在python中检查矩阵中的元素 [英] Checking elements in a matrix in python
问题描述
我有一个科学的矩阵.而且,如果满足特定条件,我会尝试将其替换为1,否则将其替换为0.
I have a matrix in scipy. And I'm trying to replace it with a 1 if it meets a certain condition, and a 0 if it doesnt.
for a in range(0,l):
for b in range(0,l):
if Matrix[a][b] == value:
Matrix[a][b] = 1
else:
Matrix[a][b] = 0
我的矩阵充满了其中包含值"的元素.但是,它给我的输出是一个完全为0的矩阵.
My matrix is full of elements that have the "value" in it. Yet it's giving me the output as a matrix that is entirely 0's.
这以前在类似的脚本上起作用.也许与矩阵的结构有关?
This worked before on a similar script. Is it perhaps something to with the structure of the matrix?
这是矩阵首先显示的样子-
Here's how the matrix looks at first--
[ [0 1. 1. 2.]
[1. 0. 2. 1.]
[1. 2. 0. 1.]
[2. 1. 1. 0.]]
当我将value设置为== 1时,我将所有1都设为1,将所有2都设为零.这就是我想要的.
When i set value == 1. I get all the 1's to 1's, and all the 2's to zero. Which is what I want.
但是,当我将value设置为== 2时,我将一切都归零.
But, when i set value == 2. I get everything to zero.
当我做所有建议的事情时.
when I do all of what has been suggested.
[[ 0. 1. 1. 2. 1. 2. 2. 3.]
[ 1. 0. 2. 1. 2. 1. 3. 2.]
[ 1. 2. 0. 1. 2. 3. 1. 2.]
[ 2. 1. 1. 0. 3. 2. 2. 1.]
[ 1. 2. 2. 3. 0. 1. 1. 2.]
[ 2. 1. 3. 2. 1. 0. 2. 1.]
[ 2. 3. 1. 2. 1. 2. 0. 1.]
[ 3. 2. 2. 1. 2. 1. 1. 0.]]
>> np.where(matrix==2,1,0)
>> array([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]])
推荐答案
如果您实际上在那里有一个矩阵,而不是一个ndarray,那么
If you actually have a matrix there, rather than an ndarray, then
Matrix[a]
是1行矩阵和2D.同样,
is a 1-row matrix, and 2D. Similarly,
Matrix[a][b]
也是一个矩阵(或IndexError,因为Matrix[a]
仅具有1行).您需要使用
is also a matrix (or an IndexError, since Matrix[a]
only has 1 row). You need to use
Matrix[a, b]
获取元素.这是为什么使用矩阵会很尴尬的原因之一.请注意,您可以只使用
to get the elements. This is one of the reasons why using matrices can be awkward. Note that you could just use
Matrix == value
获取布尔数组,然后使用astype
将其转换为所需的类型.这将减少代码量,并且运行速度更快.因此,如果您的dtype为int32,则您发布的整个循环内容都可以替换为
to get a matrix of booleans, and then use astype
to convert it to the type you want. This would be less code, and it'd run faster. Thus, if your dtype is int32, the whole loopy thing you've posted could be replaced by
return (Matrix == value).astype(numpy.int32)
,或者如果您确实要修改数组,则可以将numpy.equal
ufunc与out
参数一起使用:
or if you really want to modify the array in place, you can use the numpy.equal
ufunc with an out
parameter:
numpy.equal(Matrix, value, out=Matrix)
这篇关于在python中检查矩阵中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!