3

There are multiple questions on StackOverflow, asking how the comma syntax works, but most of them refer to m[:,n] which refers to the nth column. Similarly, m[n,:] refers to the nth row. I find this method of slicing used in the labs of Machine Learning Specialization by Andrew Ng. But does this slicing have any advantage over m[n]?

3
  • 2
    To slice a value, m[n] and m[n, :] are equivalent. The first one is maybe more explicit, this suggests that you have at least two dimensions. Commented Jun 26, 2024 at 8:06
  • 2
    (I meant the second one m[n, :] means you have at least 2D) Commented Jun 26, 2024 at 8:43
  • While leading :, are required to identify 'column' indexing, trailing : are optional. I think of numpy filling those in as needed. ... (ellipsis) occasionally is useful as well. Commented Jun 26, 2024 at 18:18

2 Answers 2

4

For an array with 2 or more dimensions, m[n] and m[n, :] are identical. The first can be considered shorthand for the second.

For an array with 1 dimension, m[n] will return element n, and m[n, :] will result in an error.

I personally would choose m[n, :] in some cases to make the code more human-readable: for example, when you know that m is two-dimensional, then m[n, :] immediately implies this to the reader, whereas m[n] might leave them having to guess at whether m is 1D or 2D.

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

Comments

0

In numpy arrays, m[:, n] accesses a specific column, offering flexibility for operations focusing on columns.

I find this particularly useful in machine learning tasks for efficient data manipulation and feature selection.

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.