如何使用 stride_tricks.as_strided 反转 NumPy 数组

问题描述 投票:0回答:1

是否可以在 NumPy 中使用

as_strided
反转数组?我尝试了以下方法并得到了垃圾结果

注意:我知道像 ::-1 这样的索引技巧,但是要知道这是否可以通过 ax_strided 来实现。

import numpy as np
from numpy.lib.stride_tricks import as_strided


elems = 16
inp_arr = np.arange(elems).astype(np.int8)

print(inp_arr)
print(inp_arr.shape)
print(inp_arr.strides)

expanded_input = as_strided(inp_arr[15],
                            shape = inp_arr.shape,
                            strides = (-1,))
print(expanded_input)
print(expanded_input.shape)
print(expanded_input.strides)

输出

[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]

(16,)

(1,)

[ 15 -113 0 21 -4 -119 -53 3 79 0 0 0 0 0 0 2]

(16,)

(-1,)

python arrays numpy
1个回答
0
投票

是的,可以,方法如下:

    import numpy as np
    from numpy.lib.stride_tricks import as_strided

    elems = 16
    inp_arr = np.arange(elems).astype(np.int8)

    print("Input Array:")
    print(inp_arr)
    print("Input Array Shape:", inp_arr.shape)
    print("Input Array Strides:", inp_arr.strides)

    # Reverse the entire input array using as_strided
    reversed_arr = as_strided(inp_arr,
                          shape=inp_arr.shape,
                          strides=(-1 * inp_arr.strides[0],))

    print("\nReversed Array:")
    print(reversed_arr)
    print("Reversed Array Shape:", reversed_arr.shape)
    print("Reversed Array Strides:", reversed_arr.strides)

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.