【问题标题】:How do I get a boolean array from an array A with multiple conditions in python?如何在 python 中从具有多个条件的数组 A 中获取布尔数组?
【发布时间】:2019-02-20 13:07:23
【问题描述】:
A = np.arange(0,20,1)
A<7

上面的代码将返回一个布尔数组,当 A

【问题讨论】:

  • 试试(A&lt;7) &amp; (A&gt;3)(例如)。

标签: python numpy numpy-ndarray


【解决方案1】:

如果你的 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])

如果你想要一个或条件,你可以用|替换&amp;

(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])

【讨论】:

    【解决方案2】:

    选择 x 值,然后:

    x = 3
    np.logical_and(x<A, A<7)
    

    【讨论】:

      【解决方案3】:

      只需使用列表推导:

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

      【讨论】:

        【解决方案4】:

        您可以使用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]
        

        【讨论】:

          【解决方案5】:
          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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-05-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-11-08
            • 2021-07-24
            相关资源
            最近更新 更多