I wanted to convert the specified elements of the NumPy array A
: 1, 5, and 8 into 0.
我想将NumPy数组A: 1、5和8的指定元素转换为0。
So I did the following:
所以我做了如下的事:
import numpy as np
A = np.array([[1,2,3,4,5],[6,7,8,9,10]])
bad_values = (A==1)|(A==5)|(A==8)
A[bad_values] = 0
print A
Yes, I got the expected result, i.e., new array.
是的,我得到了预期的结果。新数组。
However, in my real world problem, the given array (A) is very large and is also 2-dimensional, and the number of bad_values to be converted into 0 are also too many. So, I tried the following way of doing that:
然而,在我的现实问题中,给定的数组(A)非常大,而且也是二维的,要转换为0的bad_values的数量也太多了。所以,我尝试了以下方法:
bads = [1,5,8] # Suppose they are the values to be converted into 0
bad_values = A == x for x in bads # HERE is the problem I am facing
How can I do this?
我该怎么做呢?
Then, of course the remaining is the same as before.
那么,当然剩下的和以前一样。
A[bad_values] = 0
print A
1 个解决方案
#1
4
If you want to get the index of where a bad value occurs in your array A
, you could use in1d
to find out which values are in bads
:
如果你想要得到坏值在你的数组a中出现的索引,你可以使用in1d来找出坏值在哪里:
>>> np.in1d(A, bads)
array([ True, False, False, False, True, False, False, True, False, False], dtype=bool)
So you can just write A[np.in1d(A, bads)] = 0
to set the bad values of A
to 0
.
所以你可以写一个[np]in1d(A, bads)] = 0,将A的差值设为0。
EDIT: If your array is 2D, one way would be to use the in1d
method and then reshape:
编辑:如果你的数组是2D的,一种方法是使用in1d方法,然后重新塑造:
>>> B = np.arange(9).reshape(3, 3)
>>> B
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.in1d(B, bads).reshape(3, 3)
array([[False, True, False],
[False, False, True],
[False, False, True]], dtype=bool)
So you could do the following:
你可以这样做:
>>> B[np.in1d(B, bads).reshape(3, 3)] = 0
>>> B
array([[0, 0, 2],
[3, 4, 0],
[6, 7, 0]])
#1
4
If you want to get the index of where a bad value occurs in your array A
, you could use in1d
to find out which values are in bads
:
如果你想要得到坏值在你的数组a中出现的索引,你可以使用in1d来找出坏值在哪里:
>>> np.in1d(A, bads)
array([ True, False, False, False, True, False, False, True, False, False], dtype=bool)
So you can just write A[np.in1d(A, bads)] = 0
to set the bad values of A
to 0
.
所以你可以写一个[np]in1d(A, bads)] = 0,将A的差值设为0。
EDIT: If your array is 2D, one way would be to use the in1d
method and then reshape:
编辑:如果你的数组是2D的,一种方法是使用in1d方法,然后重新塑造:
>>> B = np.arange(9).reshape(3, 3)
>>> B
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.in1d(B, bads).reshape(3, 3)
array([[False, True, False],
[False, False, True],
[False, False, True]], dtype=bool)
So you could do the following:
你可以这样做:
>>> B[np.in1d(B, bads).reshape(3, 3)] = 0
>>> B
array([[0, 0, 2],
[3, 4, 0],
[6, 7, 0]])