首页 > 解决方案 > 连接两个numpy数组以使索引顺序保持不变?

问题描述

假设我有两个 numpy 数组,如下所示:

{0: array([ 2, 4, 8, 9, 12], dtype=int64),
1: array([ 1, 3, 5], dtype=int64)}

现在我想用前面的ID替换每个数组,即数组0中的值变为0,数组1中的值变为1,那么两个数组都应该合并,索引顺序必须正确。即期望的输出:

array([1, 0, 1, 0, 1, 0, 0 ,0])

但这就是我得到的:

np.concatenate((h1,h2), axis=0)
array([0, 0, 0, 0, 0, 1, 1, 1])

(如果有帮助,每个数组只包含唯一值。)

如何才能做到这一点?

标签: pythonarraysnumpy

解决方案


您对合并的描述有点不清楚。但这是有道理的

In [399]: dd ={0: np.array([ 2, 4, 8, 9, 12]), 
     ...: 1: np.array([ 1, 3, 5])}                                                             

In [403]: res = np.zeros(13, int)                                                              
In [404]: res[dd[0]] = 0                                                                       
In [405]: res[dd[1]] = 1                                                                       
In [406]: res                                                                                  
Out[406]: array([0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0])

或者使分配更清晰:

In [407]: res = np.zeros(13, int)                                                              
In [408]: res[dd[0]] = 2                                                                       
In [409]: res[dd[1]] = 1                                                                       
In [410]: res                                                                                  
Out[410]: array([0, 1, 2, 1, 2, 1, 0, 0, 2, 2, 0, 0, 2])

否则,谈话索引位置没有多大意义。


推荐阅读