该方案仅供参考、学习交流!
有时候需要查询一个list或者array中某个元素所在的位置索引,也就是行列号,对于pandas数据而言这个比较容易,但是对于一般的list或者array而言,简单的可以用list.index或者np.where等获取,但是对于部分特殊情况却无法获取,下方所构建get_index方法可适用于所有情景。
函数说明:输入参数为数据集source和需要查询位置的目标target,二者的维数可以是任意维数,数据类型可以是list也可以是array,使用时需要提前导入numpy包。返回内容为索引组成的list。
import numpy as np
def get_index(source,target):
if type(source) is not np.ndarray:
source_arr = np.array(source)
else:
source_arr = source
if type(target) is not np.ndarray:
target_arr = np.array(target)
else:
target_arr = target
source_dim = len(source_arr.shape)
target_dim = len(target_arr.shape)
target_index = []
dim_delta = source_dim - target_dim
if dim_delta == 1:
for i in range(len(source_arr)):
if (target_arr == source_arr[i]).all():
target_index.append