0

I know this question might be trivial but I am in the learning process. Given numpy 2D array, I want to take a block of rows using slicing approach. For instance, from the following matrix, I want to extract only the first three rows, so from:

[[  1   2   3   4]
 [  5   6   7   8]
 [  9  10  11  12]
 [ 28   9 203 102]
 [577 902  11 101]]

I want:

[[  1   2   3   4]
 [  5   6   7   8]
 [  9  10  11  12]]

My code here actually still missing something. I appreciate any hint.

X = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [28, 9, 203, 102], [577, 902, 11, 101]]
X = np.array(X)
X_sliced = X[3,:]
print(X_sliced)
2
  • 1
    Use X[:3] or X[:3,] instead Commented Jul 16, 2018 at 21:43
  • @user3483203 I knew it is simple but I couldn't do it. Thank you so much Commented Jul 16, 2018 at 21:45

1 Answer 1

1

Numpy matrices can be thought of as nested lists of lists. Element 1 is list 1, element 2 is list 2, and so on.

You can pull out a single row with x[n], where n is the row number you want.

You can pull out a range of rows with x[n:m], where n is the first row and m is the final row.

If you leave out n or m and do x[n:] or x[:m], Python will fill in the blank with either the start or beginning of the list. For example, x[n:] will return all rows from n to the end, and x[:m] will return all rows from the start to m.

You can accomplish what you want by doing x[:3], which is equivalent to asking for x[0:3].

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.