【问题标题】:How to Search a Number in a Numpy Array in Python如何在 Python 中搜索 Numpy 数组中的数字
【发布时间】:2019-03-14 17:56:36
【问题描述】:

在我的程序中,我想要一维数组,将其转换为二维数组,再次将其转换回一维数组,我想在最终数组中搜索一个值。为了将一维数组更改为二维数组,我使用了 numpy。我使用 where() 函数来搜索数组,最后得到以下输出:

(数组([4], dtype=int32),)

我得到了这个结果,但我只需要它的索引,以防万一。有没有一种方法可以让我只获得 where() 函数的数值结果,或者是否有另一种方法可以让我在不使用 numpy 的情况下进行 1D 到 2D 和 2D 到 1D 的转换?

import numpy as np

a = [1,2,3,4,5,6,7,8,9];
print(a)
b = np.reshape(a,(3,3))
print(b)
c = b.ravel()
print(c)
d = np.where(c==5)
print(d)

【问题讨论】:

  • where 为您提供一组数组,每个维度一个数组。应用于一维数组,它是一个 1 元素元组;应用于二维数组,它是一个 2 元素元组。 d[0] 将该数组拉出元组。顺便说一句,d 可以用作索引,例如a[d]a[4] 一样有效。
  • 或者如果你的数组按照你展示的那样排序,使用np.searchsorted(c, 5)
  • 试试print(dir(d))这会告诉你有哪些属性可用
  • np.argmax(a==5) 将为您提供数组中第一个 5 的索引。
  • @wwii 但如果 a 中没有 5 也不会抱怨。

标签: python arrays numpy multidimensional-array


【解决方案1】:

...is there an alternative way which allows me to do 1D to 2D and 2D to 1D conversions without using numpy?:

1-d 到 2-d

b = [1,2,3,4,5,6,7,8,9]
ncols = 3
new = []
for i,n in enumerate(b):
    if i % ncols == 0:
        z = []
        new.append(z)
    z.append(n)

二维到一维:How to make a flat list out of list of lists?

【讨论】:

    【解决方案2】:

    没有 numpy 版本:

    from itertools import chain
    
    a = list(range(1, 10))
    b = list(zip(*3*(iter(a),)))
    c = list(chain.from_iterable(b))
    d = c.index(5)
    

    【讨论】:

    • 我不知道为什么,但我确实喜欢 zip(*3*(iter(a),)) 的东西。
    • @wwii 不是我的发明。它是 itertools 配方之一。搜索“石斑鱼”。
    • 是的,我知道 - 我仍然喜欢它。
    • @wwii 是的,这是一个很好的小谜题,不是吗?
    【解决方案3】:
    import numpy as np
    
    a = [1,2,3,4,5,6,7,8,9];
    print(a)
    b = np.reshape(a,(3,3))
    print(b)
    c = b.ravel()
    print(c)
    d = np.where(c==5)
    print(d[0][0])
    

    【讨论】:

      【解决方案4】:

      你的情况

      print(d[0][0])
      

      将为您提供整数形式的索引。但是如果你想使用任何其他方法我建议检查Is there a NumPy function to return the first index of something in an array?

      【讨论】:

        猜你喜欢
        • 2012-10-22
        • 2021-06-03
        • 1970-01-01
        • 2014-08-02
        • 2016-07-31
        • 2016-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多