chanwcom
chanwcom

Reputation: 4650

Why is the colon needed to represent the row but not for the column of a matrix?

I've been migrating from Matlab to NumPy/Scipy. There is one fundamental thing I don't clearly understand.

When we have a two-dimensional array like the following:

x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),

in order to represent the first column and row, we use the following expressions.

col = x[:, 0]
row = x[0, ]

So ,we see that : is not needed to represent a row but : is needed for a column.

Could somebody explain what would be the reason?

Upvotes: 0

Views: 449

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122352

The slice notation uses tuples to indicate what to slice.

:, 0 is a tuple with two elements; a slice(None, None, None) object (so slicing from start to end with step 1), and the integer 0. The notation , 0 however is not valid Python. You have to have an expression before comma, you can't just leave it blank.

0, on the other hand, is a valid tuple. It contains just one element, the integer 0. Because there is more than one dimension in your array, numpy can extrapolate that you wanted to use all elements for the remaining dimensions, so you don't need to give it a 0, : (== 0, slice(None, None, None)) tuple.

Upvotes: 3

Barry Rogerson
Barry Rogerson

Reputation: 598

It is merely because [,0] is invalid syntax in Python. Whereas [0,] is perfectly legal.

Upvotes: 0

Related Questions