Reverse Part Of An Array Using Numpy
I am trying to use array slicing to reverse part of a NumPy array. If my array is, for example, a = np.array([1,2,3,4,5,6]) then I can get a slice b b = a[::-1] Which is a view o
Solution 1:
If you don't like the off by one indices
>>>a = np.array([1,2,3,4,5,6])>>>a[1:4] = a[1:4][::-1]>>>a
array([1, 4, 3, 2, 5, 6])
Solution 2:
>>>a = np.array([1,2,3,4,5,6])>>>a[1:4] = a[3:0:-1]>>>a
array([1, 4, 3, 2, 5, 6])
Solution 3:
You can use the permutation matrices (that's the numpiest way to partially reverse an array).
a = np.array([1,2,3,4,5,6])
new_order_for_index = [1,4,3,2,5,6] # Careful: index from 1 to n !# Permutation matrix
m = np.zeros( (len(a),len(a)) )
for index , new_index inenumerate(new_order_for_index ):
m[index ,new_index -1] = 1print np.dot(m,a)
# np.array([1,4,3,2,5,6])
Post a Comment for "Reverse Part Of An Array Using Numpy"