ProcolHarum
ProcolHarum

Reputation: 741

how to get subarray of matrix in python

say I have the following array j:

[[1, 2, 3, 4, 5], 
 [7, 7, 7, 6, 4], 
 [1, 1, 2, 0, 0]]

how can I get the subarray of 2x2 so the subarray would be:

[[1, 2], 
 [7, 7],]

intuitively I assumed j[0:2][0:2] would do the trick but I get:

[[1, 2, 3, 4, 5], [7, 7, 7, 6, 4]]

Upvotes: 0

Views: 578

Answers (3)

AboAmmar
AboAmmar

Reputation: 5559

You could also do:

[j[i][:2] for i in range(2)]

[[1, 2], 
 [7, 7]]

Upvotes: 0

eshirvana
eshirvana

Reputation: 24568

in numpy you can do this:

import numpy as np 
j = np.array([[1, 2, 3, 4, 5], 
 [7, 7, 7, 6, 4], 
 [1, 1, 2, 0, 0]])

j[:2, :2]

output:

>>
[[1 2]
 [7 7]]

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49803

You need to explicitly say what you want from each row:

[r[0:2] for r in j[0:2]]

Upvotes: 2

Related Questions