Vick Conan
Vick Conan

Reputation: 43

How do I shift col of numpy matrix to last col?

Say I have a numpy matrix as such:

[[1, 3, 4, 7, 8]
 [5, 6, 8, 2, 6]
 [2, 9, 3, 3, 6]
 [7, 1, 9, 3, 5]]

I want to shift column 2 of the matrix to the last column:

[[1, 4, 7, 8, 3]
 [5, 8, 2, 6, 6]
 [2, 3, 3, 6, 9]
 [7, 9, 3, 5, 1]]

How exactly do I do this?

Upvotes: 2

Views: 974

Answers (2)

Chris
Chris

Reputation: 29742

Use numpy.roll:

arr[:, 1:] = np.roll(arr[:, 1:], -1, 1)

Output:

array([[1, 4, 7, 8, 3],
       [5, 8, 2, 6, 6],
       [2, 3, 3, 6, 9],
       [7, 9, 3, 5, 1]])

How:

np.roll takes three arguments: a, shift and axis:

np.roll(a = arr[:, 1:], shift = -1, axis = 1)

This means that, take arr[:, 1:](all rows, all columns from 1), and shift it one unit to the left (-1. to the right would be +1), along the axis 1 (i.e. columnar shift, axis 0 would be row shift).

np.roll, as name states, is a circular shift. One unit shift will make last column to be the first, and so on.

Upvotes: 3

brentertainer
brentertainer

Reputation: 2188

Create a list of columns, then use that to index the array. Here, new_column_order uses a range to get all columns before col, another range to get all columns after col, then puts col at the end. Each range object is unpacked via * into the new column list.

x = np.array([[1, 3, 4, 7, 8], 
              [5, 6, 8, 2, 6], 
              [2, 9, 3, 3, 6], 
              [7, 1, 9, 3, 5]])
col = 1 # 2nd column
new_column_order = [*range(col), *range(col + 1, x.shape[-1]), col]
x_new = x[:, new_column_order]
print(x_new)

Output:

[[1 4 7 8 3]
 [5 8 2 6 6]
 [2 3 3 6 9]
 [7 9 3 5 1]]

Upvotes: 0

Related Questions