【问题标题】:How to remove certain values a Python Numpy Array如何删除 Python Numpy 数组中的某些值
【发布时间】:2021-06-03 04:03:38
【问题描述】:

我是新手,所以这可能是一个基本问题,但是如何从数组中删除小于 0 的值?

如果

a=np.random.randint(-10,11,(10,10))

如何创建一个只有来自 a 的正值的数组? 谢谢

【问题讨论】:

标签: python arrays numpy random


【解决方案1】:
import numpy as np
a=np.random.randint(-10,11,(10,10))
np.where(a > 0, a, 0)

【讨论】:

    【解决方案2】:

    本地 Python 方法是理解列表:

    filtered = [x for x in a if x>0]
    

    对于 numpy 的做法,看看这个类似的问题:Filtering a NumPy Array: what is the best approach?

    【讨论】:

      【解决方案3】:

      在 Numpy 中,您可以使用所谓的 fancy indexing 来执行此类任务。

      In [26]: a = np.random.randint(-10,11,(10,10))
      
      In [27]: a
      Out[27]:
      array([[ -6,   2,   8,  -8,  -7,   7,   5,   0,  10,   5],
             [ -3,  -7,   5,   0,   3,   7,   3,  10,  -9,   0],
             [  1,   8,  -8,  -2,   4,   2,  -7,  10,  -3,  -5],
             [  7,   1,   3,  -2,   1,   8,   7,   6,  -4,   0],
             [ -5,   6,  -2,  -7, -10,  -9,   9,   9,  -5,   8],
             [  4,   3,  -7,   1,   4,   1,  -6,   7,  -6,  -5],
             [ -5,  -5,   4,  -7,  -6,  -6,  10,  -2,  -8,   8],
             [ -9,   4,   2,  10,  -7,  -5,   3,   5,   9,   1],
             [ -9,  -7,  -3,  -8,  -4,  -7,  -6,  -5,   1,  -9],
             [ -7,  -4,  -8,   5, -10,   1,   2,  -8,  -2,  10]])
      
      In [28]: a[a!=0] #this is the fancy indexing (non 0 elements)
      Out[28]:
      array([ -6,   2,   8,  -8,  -7,   7,   5,  10,   5,  -3,  -7,   5,   3,
               7,   3,  10,  -9,   1,   8,  -8,  -2,   4,   2,  -7,  10,  -3,
              -5,   7,   1,   3,  -2,   1,   8,   7,   6,  -4,  -5,   6,  -2,
              -7, -10,  -9,   9,   9,  -5,   8,   4,   3,  -7,   1,   4,   1,
              -6,   7,  -6,  -5,  -5,  -5,   4,  -7,  -6,  -6,  10,  -2,  -8,
               8,  -9,   4,   2,  10,  -7,  -5,   3,   5,   9,   1,  -9,  -7,
              -3,  -8,  -4,  -7,  -6,  -5,   1,  -9,  -7,  -4,  -8,   5, -10,
               1,   2,  -8,  -2,  10])
      
      
      In [29]: a[a>0] #fancy indexing again (all positive elements)
      Out[29]:
      array([ 2,  8,  7,  5, 10,  5,  5,  3,  7,  3, 10,  1,  8,  4,  2, 10,  7,
              1,  3,  1,  8,  7,  6,  6,  9,  9,  8,  4,  3,  1,  4,  1,  7,  4,
             10,  8,  4,  2, 10,  3,  5,  9,  1,  1,  5,  1,  2, 10])
      

      【讨论】:

        猜你喜欢
        • 2020-02-13
        • 2019-04-30
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        • 2014-10-09
        • 1970-01-01
        • 2018-05-17
        • 1970-01-01
        相关资源
        最近更新 更多