Python Numpy高效数据处理(一)——获取数组B中每个元素在数组A中的索引值
Python Numpy高效数据处理(一)
做算法的,在工作中经常需要处理大量的数据,python中的for循环实在是太蠢了,写这篇博客主要是记录一下平时在处理大批量数据时,抛弃了for循环的新方法。本文基于python3.7
获取数组B中每个元素在数组A中的索引值
引用头
import numpy as np
import time
传统方法:for循环里使用list的index功能:
如下:
def get_index_from_array2(from_array, purpose_array):
from_list = list(from_array)
p_idx = np.in1d(purpose_array, from_array) #筛选出 purpose_array 存在于 from_array 中存在的项,防止找不到索引而报错
purpose_idx_in_from = -np.ones(purpose_array.shape).astype(int) #初始化待返回的索引数组为-1,长度对应purpose_array
in_len = p_idx.sum() #得到筛选之后的总数量
tmp_p_array = purpose_array[p_idx] #筛选之后的数组
tmp_idx = np.zeros(in_len).astype(int) #临时索引,长度对应筛选之后的数组
for i in range(in_len): #循环得到所有可获取的索引值
tmp_idx[i] = from_list.index(tmp_p_array[i])
purpose_idx_in_from[p_idx] = tmp_idx #待返回的索引数组赋值
return purpose_idx_in_from
针对所有可能的情况,A可能包含B,也可能不完全包含B,所以先做了筛选,只针对筛选出来的部分查询索引值
调用测试:
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'