简体   繁体   中英

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?

I have a numpy array. lets say

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

now

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

I need to shift x2 in such a way that the final result be

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

A fancy index and swap

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]])

You don't need to copy anything; just slice once and pass both lists of indices.

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],
# ])

I noticed you had a tensorflow tag on your question. This is a bit more involved in 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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM