【问题标题】:Return only few elements of numpy array仅返回 numpy 数组的少数元素
【发布时间】:2020-10-06 06:18:14
【问题描述】:

我有一个以下格式的 numpy 数组。如何对数组进行切片,以便我只得到 1。

array([[1, 2, 1, ..., 2, 2, 2],
       [1, 1, 1, ..., 2, 2, 2],
       [1, 1, 1, ..., 2, 2, 2],
       ...,
       [1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1],
       [1, 1, 1, ..., 1, 1, 1]])

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    假设您的数组名称是 a。

    a = a[np.where(a == 1)]
    

    【讨论】:

      【解决方案2】:

      试试这样的。

      for a in array:
         if a == 1:
           print(a)
      

      如果您想存储这些值(而不是打印它们),请尝试这样的操作。

      ab = [1, 2, 1, ..., 2, 2, 2]
          
      numberList = []
              
      def numbers(array):
        for a in array:
          if a == 1:
           numberList.append(a)
                  
      numbers(ab)
      print(numberList)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-31
        • 2013-01-22
        • 1970-01-01
        相关资源
        最近更新 更多