【问题标题】:finding the position of an element within a numpy array in python [duplicate]在python中找到一个numpy数组中元素的位置[重复]
【发布时间】:2020-05-23 01:45:22
【问题描述】:

我想问一个关于在 Python 的 numpy 包中查找数组中元素位置的问题。

我正在使用适用于 Python 3 的 Jupyter Notebook,下面的代码如下所示:

concentration_list = array([172.95, 173.97, 208.95])

我想编写一段代码,它能够返回数组中元素的位置。

为此,我想用172.95来演示。

最初,我尝试使用.index(),在括号内传入172.95,但这不起作用,因为numpy无法识别.index()方法-

concentration_position = concentration_list.index(172.95)

AttributeError: 'numpy.ndarray' object has no attribute 'index'

当我访问该站点时,Sci.py 文档没有提到任何关于这种方法可用的信息。

是否有任何可用的功能(我可能没有发现)来解决问题?

【问题讨论】:

标签: python numpy


【解决方案1】:

您可以通过numpy 库中的where 函数

import numpy as np

concentration_list = np.array([172.95, 173.97, 208.95])
number = 172.95

print(np.where(concentration_list == number)[0])


Output : [0]

【讨论】:

  • 来自numpy.where() 的文档:当仅提供条件时,此函数是 np.asarray(condition).nonzero() 的简写。应该首选直接使用非零值,因为它对子类表现正确。
【解决方案2】:

为此目的使用np.where(...),例如

import numpy as np

concentration_list = np.array([172.95, 173.97, 208.95])

index=np.ravel(np.asarray(concentration_list==172.95).nonzero())

print(index)

#outputs (array of all indexes matching the condition):

>> [0]

【讨论】:

  • 来自numpy.where() 的文档:当仅提供条件时,此函数是 np.asarray(condition).nonzero() 的简写。应该首选直接使用非零值,因为它对子类表现正确。
  • 调整了!干杯!
猜你喜欢
  • 1970-01-01
  • 2017-12-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 2022-06-19
相关资源
最近更新 更多