0

Right now I have a 2x2 ND-array, namely np.array([[93, 95], [84, 100], [99, 87]]). I would like to reverse the second column of the array into, such that I get: np.array([[93, 87], [84, 100], [99, 95]]).

I tried the following code:

grades = np.array([[93,  95], [84, 100], [99,  87]])
print(grades[::-1,:])

However, the result I get is

[[ 99  87]
 [ 84 100]
 [ 93  95]]

I understand that this is because I am reversing all of the entries in the 1-axis, which is why the entries in the first column is also reversed. So what code can I write to get:

[[ 93  87]
 [ 84 100]
 [ 99  95]]
Willow
  • 3
  • 1
  • 1
    Select the column you want to reverse, apply the `::-1`, and then copy that back. Do the the most obvious thing, rather than seek something magical. – hpaulj Feb 20 '23 at 07:44

1 Answers1

0

Use numpy.flip function to reverse the order of values in specific column(s), though it's more suitable for a more extended/general cases:

grades = np.array([[93,  95], [84, 100], [99,  87], [99, 83]])
grades[:, -1] = np.flip(grades[:, -1])
print(grades)

Or just use the reversed order of rows:

grades[:, -1] = grades[::-1, -1]

[[ 93  83]
 [ 84  87]
 [ 99 100]
 [ 99  95]]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • Can there be a more general solution to the problem? For example instead of a 3x2 array, I have a 4x2 array such as `[[93, 95], [84, 100], [99, 87],[99,83]]` and want to change it into `[[93, 83], [84, 87], [99, 100],[99,95]]` – Willow Feb 20 '23 at 07:09
  • @Willow, update your initial question with extended requirement – RomanPerekhrest Feb 20 '23 at 07:39