Roman
Roman

Reputation: 3241

extract elements from rows/columns

import numpy as np
data = np.arange(35).reshape(7,5)
print (data)

enter image description here

I wanted to extract elements inside red.

result = data[-3:, -2:]

print (result)

[[23 24]
 [28 29]
 [33 34]]

wrong!

how is correct?

Upvotes: 0

Views: 58

Answers (2)

user9703439
user9703439

Reputation:

elegant and perfect:

result = data[-3:, :3]

Upvotes: 1

user3483203
user3483203

Reputation: 51185

You're very close, but your -2 is on the wrong side of the :

You want to access from the last 3 rows, but only up until the last 2 columns:

In [52]: data[-3:, :-2]
Out[52]:
array([[20, 21, 22],
       [25, 26, 27],
       [30, 31, 32]])

-2: == Last two columns

:-2 == Up until the last two columns

If you explicitly want the last 3 rows and the first 3 columns, you could also use:

In [53]: data[-3:, :3]
Out[53]:
array([[20, 21, 22],
       [25, 26, 27],
       [30, 31, 32]])

Upvotes: 1

Related Questions