python - 如何提取 numpy 数组中值的索引?

标签 python arrays numpy

这是场景:

我有以下变量:

val = [('am', '<f8'), ('fr', '<f8')] # val is type numpy.recarray     

am = [12.33, 1.22, 5.43, 15.23]  # am is type numpy.ndarray  

fr = [0.11, 1.23, 2.01, 1.01]   # fr is type numpy.ndarray  

我需要的是在提取后检测 am = 12.33am = 15.23 的索引(在本例中索引为 [0][3]),我需要创建新变量:

new_am = [12.33, 15.23] 

new_fr = [0.11, 1.01] 

我的问题是:知道如何提取索引吗?

我已经使用了 .indexnp.where 但似乎有问题,因为我收到了 .index 的错误消息:

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

对于np.where返回的索引什么都不是array([], dtype=int64)

感谢您的任何想法!

最佳答案

您可能需要 np.in1d 返回一个 bool 值数组来指示某个元素是否在另一个数组中:

import numpy as np
am = np.array([12.33, 1.22, 5.43, 15.23]) 
fr = np.array([0.11, 1.23, 2.01, 1.01])

index = np.where(np.in1d(am, [12.33, 15.23]))[0]
index
# array([0, 3])

am[index]
# array([ 12.33,  15.23])

fr[index]
# array([ 0.11,  1.01])

或者也许你有一个带有属性的数组:

new_arr = np.array(zip(am, fr), dtype=val)

index = np.where(np.in1d(new_arr['am'], [12.33, 15.23]))[0]

new_am = new_arr[index]['am']
new_fr = new_arr[index]['fr']

new_am
# array([ 12.33,  15.23])

new_fr
# array([ 0.11,  1.01])

关于python - 如何提取 numpy 数组中值的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41354421/

相关文章:

python - 将curl转换为python

python - 我的 python 代码拒绝为我正在制作的这个不和谐机器人运行

python - 如果其中一个轴的 set_aspectratio 为 "equal",则轴的大小相同

python - 取消广播 Numpy 数组

python - Scikit-learn 的 GridSearchCV 中的 Grid_scores_ 是什么意思

Python简单 turtle 程序

c - 打印一个字符数组(C)只有第一个字母

c# - 使用 for 循环将自定义对象分配给数组?

python - 如何在 Python 中填充二维数组?

python - 奇怪的 numpy.float96 行为