如果我有这样的Numpy数组:
array([0, 0, 0]
[0, 0, 1]
[0, 1, 2]
[0, 1, 3]
[1, 0, 4]
[1, 0, 5]
[1, 1, 6]
[1, 1, 7])
我尝试使用
if c==1 in range(X[:,2]):
print 'yes'
但得到错误
TypeError: only length-1 arrays can be converted to Python scalars
是否可以使用切片和c==1
语句找到if
?
答案 0 :(得分:2)
由于x[:,2]
为您提供第三列
>>> import numpy as np
>>> x = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 2], [0, 1, 3], [1, 0, 4], [1, 0, 5], [1, 1, 6], [1, 1, 7]])
>>> x
array([[0, 0, 0],
[0, 0, 1],
[0, 1, 2],
[0, 1, 3],
[1, 0, 4],
[1, 0, 5],
[1, 1, 6],
[1, 1, 7]])
>>> x[:,2]
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> if 1 in x[:,2]:
... print("yes")
...
yes
最有效率的
>>> if np.any(x[:, 2] == 1):
... print("yes")
...
yes
>>>
答案 1 :(得分:1)
您可以在此处使用布尔索引(而不是循环使用if
)。这是您使用True
/ False
值数组来挑选所需数组的行或列或值的地方。
在第三列中需要用来查找1
行的布尔数组是:
>>> X[:, 2] == 1
array([False, True, False, False, False, False, False, False], dtype=bool)
这将返回一个新数组,其中包含X
每行的值。如果第三列的值为True
,则1
包含False
。
(您可以看到,如果您查找第三列的值以查找1
,这就是您所获得的。)
要在第三列中返回X
的行1
,只需使用此布尔数组来索引X
:
>>> X[X[:, 2] == 1]
array([[0, 0, 1]])