如何从具有多个条件的数组A的python中获取布尔数组?

时间:2019-02-20 13:07:23

标签: python numpy numpy-ndarray

A = np.arange(0,20,1)
A<7

上面的代码将返回一个布尔数组,其中当A <7时其元素为true,否则为false。 如何获得x

5 个答案:

答案 0 :(得分:3)

如果您的x = 3,则:

a = np.arange(0,20,1)
a
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])

(a>3) & (a<7)
array([False, False, False, False,  True,  True,  True, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False])

如果您想要一个或条件,可以将&替换为|

(a<3) | (a>7) #Less than 3 or greater than 7
array([ True,  True,  True, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True])

答案 1 :(得分:2)

选择x值,然后:

npm i -g electron-packager

答案 2 :(得分:1)

只需使用列表理解:

x = 3
bools = [i<7 and i> x for i in A]

答案 3 :(得分:1)

import timeit

A = np.arange(0, 20, 1)
# print(A)
x = 3


def fun():
    return [x < i < 7 for i in A]


def fun2():
    return (A < 7) & (A > 3)


def fun3():
    return np.logical_and(x < A, A < 7)

def fun4():
    return [i < 7 and i > x for i in A]


print('fun()', timeit.timeit('fun()', number=10000, globals=globals()))
print('fun2()', timeit.timeit('fun2()', number=10000, globals=globals()))
print('fun3()', timeit.timeit('fun3()', number=10000, globals=globals()))
print('fun4()', timeit.timeit('fun4()', number=10000, globals=globals()))

输出:

执行时间(以秒为单位):

fun() 0.055701432000205386
fun2() 0.016561345997615717
fun3() 0.016588653001235798
fun4() 0.0446821750010713

答案 4 :(得分:1)

您可以将numpy.logical_and用于该任务,例如:

import numpy as np
A = np.arange(0,20,1)
B = np.logical_and(3<A,A<7)
print(B)

输出:

[False False False False  True  True  True False False False False False
 False False False False False False False False]