这是场景:
我有以下变量:
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.33
和 am = 15.23
的索引(在本例中索引为 [0]
和 [3]
),我需要创建新变量:
new_am = [12.33, 15.23]
new_fr = [0.11, 1.01]
我的问题是:知道如何提取索引吗?
我已经使用了 .index
和 np.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/