谢谢哦!
5条回答 默认 最新
- 歇歇 2021-02-06 18:13关注
开始
import numpy as np import time
采用numpy数组操作,避开循环
def get_index_from_array(from_array, purpose_array): purpose_array = np.array(purpose_array) from_array = np.array(from_array) purpose_idx_in_from = -np.ones(purpose_array.shape).astype(int) #初始化待返回的索引数组为-1,长度对应purpose_array p_idx = np.in1d(purpose_array, from_array) #筛选出 purpose_array 存在于 from_array 中存在的项 union_array = np.hstack((from_array, purpose_array[p_idx])) #合并from_array 和从 purpose_array 中筛选出来的数组 _, union_idx, union_inv = np.unique(union_array, return_index=True, return_inverse=True) #unique函数得到索引值 purpose_idx_in_from[p_idx] = union_idx[union_inv[len(from_array):]] #待返回的索引数组赋值 return purpose_idx_in_from
测试
purpose_array = np.array(['b', 't', 'd', 'g', 'f', 'f', 'g', 'b', 'g', 'f', 'p', 'd', 'f', 'r', 'g', 'w', 't', 'd', 'e', 'b', 'e']) from_array = np.array(['e', 'c', 'f', 'a', 'e', 'g', 'f', 'a', 'b', 'd', 'd', 'e']) idx = get_index_from_array(from_array, purpose_array) print(idx) pos_idx = (idx != -1) test_a = purpose_array[pos_idx] test_b = from_array[idx[pos_idx]] print((test_a == test_b).all())
unique函数
from_array = np.array(['e', 'c', 'f', 'a', 'e', 'g', 'f', 'a', 'b', 'd', 'd', 'e']) test = np.unique(from_array, True, True, True) print(test)
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用