使用查找表将n个2D数组转换为单个数组

时间:2017-09-14 18:39:49

标签: python arrays numpy

我有一系列n个2D数组,它们作为深度为n的3D数组呈现给函数。我想沿第三轴生成每组值的元组,然后用一个索引值和一个查找表替换每个元组。

我在python中工作,有一些大型数据集,所以它需要可扩展,所以可能会使用numpy。其他解决方案也被接受。

这是我到目前为止所得到的:

In [313]: arr=np.array([[[0,0,0],[1,2,2],[3,0,0]],[[0,1,0],[1,3,2],[0,0,0]]])

In [314]: stacked = np.stack((arr[0], arr[1]), axis=2)

In [315]: pairs = stacked.reshape(-1, arr.shape[0])

In [316]: pairs
Out[316]:
array([[0, 0],
       [0, 1],
       [0, 0],
       [1, 1],
       [2, 3],
       [2, 2],
       [3, 0],
       [0, 0],
       [0, 0]])

In [317]: unique = set([tuple(a) for a in pairs])

In [318]: lookup = sorted(list(unique))

In [319]: lookup
Out[319]: [(0, 0), (0, 1), (1, 1), (2, 2), (2, 3), (3, 0)]

现在,我想使用查找表中值的索引创建一个输出数组,因此输出将为:

[0, 1, 0, 2, 4, 3, 5, 0, 0]

此示例仅包含两个输入2D数组,但可能还有更多。

1 个答案:

答案 0 :(得分:0)

所以,我提出了一个产生我想要的输出的解决方案,但它是最有效的方法吗?特别是,lookup.index调用有点贵。有没有人有更好的方法?

getProducts(){
     return this.storage.get('Authorization').then((value)=>{
       this.token= value;
       return this.sendReq(this.token)
     });
}

sendReq(token){
      let headers = new Headers();       
      headers.append("Authorization",token);
      return this.http.get('https://vjtest.cobold.xyz/vapi/public/api/products',{headers: headers})
      .map(res=> res.json());
}