Reputation: 287
My goal is to shift the columns of an array B
k
positions to the left. Assume B
is of the shape (n,n)
. Then of course, the columns from n
to n-k
have to replaced with some new entries. But this shouldn't be of importance here. What does work is the following:
for i in range(n):
for j in range(n-k):
B[i][j] = B[i][j+k]
I wonder if there is a faster and simpler method. Any suggestions appreciated
Upvotes: 1
Views: 53
Reputation: 42143
You could use subscripts:
B = B[k:] + newValues
or, if you want to keep the array size and manipulate the original positions afterward:
B[:k] = B[k:2*k]
note that, in this last approach, you must have 2k <= n otherwise you won't have enough elements to fill the left side of the array
Upvotes: 0
Reputation: 10917
If you were using your matrix in column-major order (i.e. using i
as column index), much less copies would be needed
for j in range(n-k):
B[i] = B[i+k]
in this case only the reference to the column is copied
Upvotes: 1