-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])
2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.