如何用指定列表的索引替换数组的所有项?

2024-10-04 11:23:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用ID替换sequence的所有项,这些ID告诉它们在哪个标签列表中。假设所有值在sequencelabeller中都是不同的,并且labeller列表的并集具有与sequence相同的项lsizes对应于labeller中列表的大小,对于Pythonic解决方案是多余的,但对于完全向量化的解决方案可能是必需的

sequence = [1, 2, 10, 5, 6, 4, 3, 8, 7, 9],
labeller = [[1, 2, 10], [3, 4, 5, 6, 7], [8, 9]]
lsizes = [3, 5, 2]

我知道如何用一种简单的方法解决它:

idx = {u:i for i, label in enumerate(labeller) for u in label}
tags = [idx[u] for u in sequence]

输出为:

tags = [0, 0, 0, 1, 1, 1, 1, 2, 1, 2]

在那之后,我把我所有的努力都用矢量化的方式来做。这对我来说相当复杂。这是我的尝试,只是猜测而已,但不幸的是,它没有通过我所有的测试。我希望我很接近:

sequence = np.array(sequence)
cl = np.concatenate(labeller)
_, cl_idx = np.unique(cl, return_index=True)
_, idx = np.unique(sequence[cl_idx], return_index=True)
tags = np.repeat(np.arange(len(lsizes)), lsizes)[idx]
#output: [0 0 1 1 0 1 1 1 2 2]

我怎样才能完成它?我也希望看到严谨的解释,它做什么以及如何更好地理解它。也欢迎任何来源


Tags: inid列表forreturnclnptags
2条回答

方法#1

对于那些追溯问题,^{}似乎是一种方法,在这里也可以使用,重新使用cl-

cl = np.concatenate(labeller)
sidx = cl.argsort()
idx = np.searchsorted(cl, sequence, sorter=sidx)
idx0 = sidx[idx]

l = list(map(len, labeller))
r = np.repeat(np.arange(len(l)), l)
out = r[idx0]

l使用lsizes使其完全矢量化。但是,我怀疑连接步骤可能很繁重。这是否值得,在很大程度上取决于子阵列的长度

方法#2

对于正数,这里有一个数组索引作为散列机制-

N = max(map(max, labeller))+1
id_ar = np.zeros(N, dtype=int) # use np.empty for perf. boost
for i,l in enumerate(labeller):
    id_ar[l] = i
out = id_ar[sequence]
sequence = [1, 2, 10, 5, 6, 4, 3, 8, 7, 9]
labeller = [[1, 2, 10], [3, 4, 5, 6, 7], [8, 9]]
lsizes = [3, 5, 2]

sequence_array = np.array(sequence)
labeller_array = np.array(labeller).sum()
index_array = np.repeat(list(range(len(lsizes))), lsizes)

np.apply_along_axis(lambda num : index_array[np.where(labeller_array == num)[0]], 0, sequence_array[None, :])
# output: array([[0, 0, 0, 1, 1, 1, 1, 2, 1, 2]])

备选方案:

label_df = pd.DataFrame({'label':labeller_array, 'index':index_array})
seq_df = pd.DataFrame({'seq':sequence_array})
seq_df.merge(label_df, left_on = 'seq', right_on = 'label')['index'].tolist()
#output: [0, 0, 0, 1, 1, 1, 1, 2, 1, 2]

相关问题 更多 >