gpt4 book ai didi

python - 重新排序一个numpy数组python

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:40 36 4
gpt4 key购买 nike

我有一个像这样的大二维数组:

array([[ 1, 2, 3, 4, 5, 6, 7, 8],
[ 9,10,11,12,13,14,15,16],
[17,18,19,20,21,22,23,24],
[25,26,27,28,29,30,31,32],
[33,34,35,36,37,38,39,40],
[41,42,43,44,45,46,47,48],
....])

我需要将它转换成:

array([ 1, 9,17, 2,10,18, 3,11,19, 4,12,20, 5,13,21, 6,14,22, 7,15,23, 8,16,24],
[25,33,41,26,34,42,27,35,43,28,36,44,29,37,45,30,38,46,31,39,47,32,40,48],
...

请注意,这应该只是演示它应该做什么。
原始数组仅包含 bool 值,大小为 512x8。在我的示例中,我只将 3 行 8 个元素排列成一行,但我真正需要的分别是 32 行 8 个元素。

我真的很抱歉,但是在写了 30 分钟之后,这是我对我的问题的唯一描述。我希望这足够了。

最佳答案

我认为您可以使用两个 reshape 来达到您想要的结果操作和 transpose :

x = np.array([[ 1, 2, 3, 4, 5, 6, 7, 8],
[ 9,10,11,12,13,14,15,16],
[17,18,19,20,21,22,23,24],
[25,26,27,28,29,30,31,32],
[33,34,35,36,37,38,39,40],
[41,42,43,44,45,46,47,48]])

y = x.reshape(2, 3, 8).transpose(0, 2, 1).reshape(2, -1)

print(repr(y))
# array([[ 1, 9, 17, 2, 10, 18, 3, 11, 19, 4, 12, 20, 5, 13, 21, 6, 14,
# 22, 7, 15, 23, 8, 16, 24],
# [25, 33, 41, 26, 34, 42, 27, 35, 43, 28, 36, 44, 29, 37, 45, 30, 38,
# 46, 31, 39, 47, 32, 40, 48]])

稍微分解一下:

  1. @hpaulj 的第一个 reshape 操作为我们提供了这个:

    x1 = x.reshape(2, 3, 8)
    print(repr(x1))
    # array([[[ 1, 2, 3, 4, 5, 6, 7, 8],
    # [ 9, 10, 11, 12, 13, 14, 15, 16],
    # [17, 18, 19, 20, 21, 22, 23, 24]],

    # [[25, 26, 27, 28, 29, 30, 31, 32],
    # [33, 34, 35, 36, 37, 38, 39, 40],
    # [41, 42, 43, 44, 45, 46, 47, 48]]])
    print(x1.shape)
    # (2, 3, 8)
  2. 为了获得所需的输出,我们需要沿第二个维度(大小为 3)“折叠”此数组,然后沿第三个维度(大小为 8)“折叠”。实现这种事情的最简单方法是首先 transpose数组,以便您要折叠的维度从头到尾排序:

    x2 = x1.transpose(0, 2, 1)  # you could also use `x2 = np.rollaxis(x1, 1, 3)`
    print(repr(x2))
    # array([[[ 1, 9, 17],
    # [ 2, 10, 18],
    # [ 3, 11, 19],
    # [ 4, 12, 20],
    # [ 5, 13, 21],
    # [ 6, 14, 22],
    # [ 7, 15, 23],
    # [ 8, 16, 24]],

    # [[25, 33, 41],
    # [26, 34, 42],
    # [27, 35, 43],
    # [28, 36, 44],
    # [29, 37, 45],
    # [30, 38, 46],
    # [31, 39, 47],
    # [32, 40, 48]]])
    print(x2.shape)
    # (2, 8, 3)
  3. 最后,我可以使用 reshape(2, -1) 在最后两个维度上折叠数组。 -1 导致 numpy 根据 x 中的元素数量推断最后一个维度中的适当大小。

    y = x2.reshape(2, -2)

关于python - 重新排序一个numpy数组python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33507257/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com