1

Recently someone told me to extract the first two columns of a 2D numpy.ndarray by

firstTwoCols = some2dMatrix[:2]

Where is this notation from and how does it work?

I'm only familiar with the comma separated slicing like

twoCols = some2dMatrix[:,:2]

The : before the comma says to get all rows, and the :2 after the comma says for columns 0 up to but not including 2.

3 Answers 3

4

firstTwoCols = some2dMatrix[:2]

This will just extract the first 2 rows with all the columns.

twoCols = some2dMatrix[:,:2] is the one that will extract your first 2 columns for all the rows.

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

Comments

2

The syntax you describe does not extract the first two columns; it extracts the first two rows. If you specify less slices than the dimension of the array, NumPy treats this as equivalent to all further slices being :, so

arr[:2]

is equivalent to

arr[:2, :]

for a 2D array.

Comments

-1

Not sure I understand the question but...

If you do:

>>> Matrix = [[x for x in range(1,5)] for x in range(5)] 
>>> Matrix
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

doing Matrix[:2], it will select the first two list in Matrix, [1, 2, 3, 4], [1, 2, 3, 4]. But if you do:

>>> Matrix[:,:2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

But if you work with a Numpy, do:

Matrix = np.array(Matrix)

>>>Matrix[:, :2]
array([[1, 2],
       [1, 2],
       [1, 2],
       [1, 2],
       [1, 2]])

2 Comments

The comma-separated slicing thing is NumPy syntax.
@user2357112 oh cool! I didn't know... I updated my answer. Thanks!

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.