Reason why numpy rollaxis is so confusing?

后端 未结 3 640
有刺的猬
有刺的猬 2020-12-18 20:19

The behavior of the numpy rollaxis function confuses me. The documentation says:

Roll the specified axis backwards, until it lies in a given position.

3条回答
  •  猫巷女王i
    2020-12-18 20:46

    NumPy v1.11 and newer includes a new function, moveaxis, that I recommend using instead of rollaxis (disclaimer: I wrote it!). The source axis always ends up at the destination, without any funny off-by-one issues depending on whether start is greater or less than end:

    import numpy as np
    
    x = np.zeros((1, 2, 3, 4, 5))
    for i in range(5):
        print(np.moveaxis(x, 3, i).shape)
    

    Results in:

    (4, 1, 2, 3, 5)
    (1, 4, 2, 3, 5)
    (1, 2, 4, 3, 5)
    (1, 2, 3, 4, 5)
    (1, 2, 3, 5, 4)
    

提交回复
热议问题