【问题标题】:How can I shift columns of numpy array so that the first two colums go to the last and the last two come to the first?如何移动 numpy 数组的列,以便前两列到最后一列,最后两列到第一列?
【发布时间】:2019-12-07 08:42:05
【问题描述】:

我有一个 numpy 数组。让我们说

x=([8, 9, 0, 1, 2, 3, 4, 5, 6, 7,12,13])
x2 = np.reshape(x, (2,6))

现在

x2= [[ 8  9  0  1  2  3]
     [ 4  5  6  7 12 13]]

我需要移动 x2 以使最终结果为

X3=[[2  3   0  1  8   9]
    [12 13  6  7  4   5]]

【问题讨论】:

  • 您尝试过什么了吗?你看过 hstackvstack 等函数了吗?

标签: python arrays numpy tensorflow machine-learning


【解决方案1】:

你不需要复制任何东西;只需切片一次并传递两个索引列表。

import numpy as np


x = np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 12, 13])
x = x.reshape(x, [2, 6])
x = x[:, [[0, -2], [1, -1]]] = x[:, [[-2, 0], [-1, 1]]]
x

# array([
#   [ 2,  3,  0,  1,  8,  9],
#   [12, 13,  6,  7,  4,  5],
# ])

我注意到你的问题上有一个 tensorflow 标签。这在张量流中涉及更多。

import tensorflow as tf


x = tf.constant([
    [8, 9, 0, 1, 2, 3],
    [4, 5, 6, 7, 12, 13],
])

idx = tf.constant([
    [[0, 4], [0, 5], [0, 2], [0, 3], [0, 0], [0, 1]],
    [[1, 4], [1, 5], [1, 2], [1, 3], [1, 0], [1, 1]],
])

shp = tf.constant([2, 6])

swapped = tf.scatter_nd(indices=idx, updates=x, shape=shp)

with tf.Session() as sess:
    print(swapped.eval(session=sess))

# [[ 2  3  0  1  8  9]
#  [12 13  6  7  4  5]]

【讨论】:

  • 实际上,我正在使用 TensorFlow,但它的数组问题。我有 361 个形状数组(39*200),我想将前 45 列移到最后一列,将最后一列移到第一列。
【解决方案2】:

一个花哨的索引和交换

x2[:, 0:2], x2[:, -2:] = x2[:, -2:].copy(), x2[:, 0:2].copy()

Out[117]:
array([[ 2,  3,  0,  1,  8,  9],
       [12, 13,  6,  7,  4,  5]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 2010-12-08
    • 2021-01-19
    • 2018-06-02
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多