【问题标题】:Find index of all elements numpy arrays查找所有元素的索引numpy数组
【发布时间】:2019-07-12 06:55:36
【问题描述】:

我正在使用numpy searchsort() 函数来查找numpy 数组的索引。它仅适用于某些阵列。出了什么问题(下面的实现)?

import numpy as np

#specify the dtype in RV
RV = np.array([
  np.array([0.23, 2.5, 5.0, 7.1]),
  np.array(['a1', 'a2']),
  np.array(['b2', 'b1'])
], dtype=object) 
print(RV)
def Rules():
    global r  
    r = np.array(np.meshgrid(*RV), dtype=object).T.reshape(-1,len(RV))
    return r
Rules()
print(r)

print(RV[0].searchsorted(r[:,0])) #working
print(RV[1].searchsorted(r[:,1])) #working
print(RV[2].searchsorted(r[:,2])) #not working 

【问题讨论】:

  • 既然RV[2] 未排序,请使用sorter arg。

标签: python python-3.x numpy indexing


【解决方案1】:

默认情况下,searchsorted()array 参数必须是一个排序。因此解决方案是:

使用numpy.sort()提前排序:

np.sort(RV[2]).searchsorted(r[:,2])

或者使用sorter 参数:

RV[2].searchsorted(r[:,2],sorter=np.argsort(RV[2]))

【讨论】:

    猜你喜欢
    • 2018-09-25
    • 1970-01-01
    • 2017-12-01
    • 2016-09-24
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 2013-06-26
    相关资源
    最近更新 更多