在保留更多子列表的同时,在python中使成员向量脱离元组 [英] Make member vectors out of tuples in python while preserving further sub-listings

查看:56
本文介绍了在保留更多子列表的同时,在python中使成员向量脱离元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组.

I have a numpy array.

a = np.array([[1,2], [2,4], [3,6]])
and `np.array([[1,2,3],[2,4,6]])` is wanted.

并且在这个问题中,我们确定要获取两对要对齐的2个单独的新向量,每个对成员对应一个向量,我们应该使用矩阵的a.T换位.

And in this question it was established that to get the pairs to align in 2 separate new vectors, one for each pair-member, we should use a.T transposition of the matrix.

但是,如果进一步嵌入numpy数组,这将不适用.

However this does not apply if numpy arrays are further embedded.

>>>b
array([[[1, 2],
        [3, 4]],
       [[1, 2],
        [3, 4]],
       [[1, 2],
        [3, 4]],
       [[1, 2],
        [3, 4]]])

我想要:

>>>b.operation
    array([[[1, 2],[1, 2],[1, 2],[1, 2]]
           [[3, 4],[3, 4],[3, 4],[3, 4]]])

但是我得到

>>>b.T
array([[[1, 1, 1, 1],
        [3, 3, 3, 3]],
       [[2, 2, 2, 2],
        [4, 4, 4, 4]]])

这当然是有道理的,因为换位似乎会颠倒形状. (4, 2, 2) -> (2, 2, 4)但是

Which of course makes sense, since transposition seems to flip the shape around. (4, 2, 2) -> (2, 2, 4) But

我也尝试过重新分配形状,但是我想看看它在内存中的位置:

I also tried reassigning the shape, but I guess looking at how it lies in memory:

b in mem : 1234123412341234
b.T in mem : 1111333322224444

这是行不通的.

i'd need : 1212121234343434

关于如何正确或有效地处理此问题的任何建议?

Any advice in how to handle this properly or in an efficient way?

推荐答案

使用 numpy数组操作例程.

对于您的用例,这演示了所需的用法:

For your use case, this demonstrates the desired usage:

In [1]: a = np.array([[1,2], [2,4], [3,6]])

In [2]: b = np.array([
   ...:     [[1, 2],
   ...:      [3, 4]],
   ...:     [[1, 2],
   ...:      [3, 4]],
   ...:     [[1, 2],
   ...:      [3, 4]],
   ...:     [[1, 2],
   ...:      [3, 4]]])
   ...:

In [3]: np.moveaxis(a, 0, 1)
Out[3]:
array([[1, 2, 3],
       [2, 4, 6]])

In [4]: np.moveaxis(b, 0, 1)
Out[4]:
array([[[1, 2],
        [1, 2],
        [1, 2],
        [1, 2]],

       [[3, 4],
        [3, 4],
        [3, 4],
        [3, 4]]])

在编辑此答案之前,我建议 np .rollaxis (在这种情况下,您将使用np.rollaxis(a, 1)),但随后我在链接的文档中注意到建议使用np.moveaxis.

Before editing this answer I recommended np.rollaxis (in which case you would use np.rollaxis(a, 1)), but then I noticed in that linked documentation that np.moveaxis is recommended.

这篇关于在保留更多子列表的同时,在python中使成员向量脱离元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆