-1

How can I get data from a specific row and column range?

For example, I have a 5X5 array. I would like to get data in row 1~3 and column 1~3?

I know there are other answers talking about getting data in columns, but I don't want the whole columns. Need help~

enter image description here

This is the coding I use to get the whole column.

import numpy as np
m = np.array(np.random.random((5, 5)))
print(m)
#Getting column 1,2
print(m[:,[1, 2]])
#Getting column 1~3
print(m[:,1:4])
Joanne
  • 503
  • 1
  • 3
  • 15
  • 1
    Does this answer your question? [Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?](https://stackoverflow.com/questions/4257394/slicing-of-a-numpy-2d-array-or-how-do-i-extract-an-mxm-submatrix-from-an-nxn-ar) – David Buck Feb 19 '20 at 23:33
  • 1
    Have you read the NumPy docs? – AMC Feb 19 '20 at 23:36

2 Answers2

2

Just slice in both dimensions at once:

import numpy as np
m = np.array(np.random.random((5, 5)))
print(m[1:4,1:4])
[[0.92383161 0.76857191 0.39590632]
 [0.84968982 0.50103819 0.72481367]
 [0.2130214  0.61815567 0.55792883]]

Remember that python excludes the end-point of the slice, hence 1:4 instead of 1:3.

xletmjm
  • 257
  • 1
  • 3
1

Easy, you do the same slicing with the rows as you do with the columns:

import numpy as np
m = np.array(np.random.random((5, 5)))
print(m)
#Getting column 1,2
print(m[:,[1, 2]])
#Getting column 1~3
print(m[:,1:4])
#Getting rows 1~3 and columns 1~3
print(m[1:4,1:4])
adam
  • 94
  • 4