I tend to index numpy arrays (matrices) with brackets, but I've noticed when I want to slice an array (matrix) I must use the comma notation. Why is this? For example,
>>> x = numpy.array([[1, 2], [3, 4], [5, 6]]) >>> x array([[1, 2], [3, 4], [5, 6]]) >>> x[1][1] 4 # expected behavior >>> x[1,1] 4 # expected behavior >>> x[:][1] array([3, 4]) # huh? >>> x[:,1] array([2, 4, 6]) # expected behavior
A parenthesized number followed by a comma denotes a tuple with one element. The trailing comma distinguishes a one-element tuple from a parenthesized n . In a dimension entry, instructs NumPy to choose the length that will keep the total number of array elements the same.
Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
There are several important differences between NumPy arrays and the standard Python sequences: NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically). Changing the size of an ndarray will create a new array and delete the original.
Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python's in-built container objects. As mentioned earlier, items in ndarray object follows zero-based index. Three types of indexing methods are available − field access, basic slicing and advanced indexing.
This:
x[:, 1]
means "take all indices of x
along the first axis, but only index 1 along the second".
This:
x[:][1]
means "take all indices of x
along the first axis (so all of x
), then take index 1 along the first axis of the result". You're applying the 1
to the wrong axis.
x[1][2]
and x[1, 2]
are only equivalent because indexing an array with an integer shifts all remaining axes towards the front of the shape, so the first axis of x[1]
is the second axis of x
. This doesn't generalize at all; you should almost always use commas instead of multiple indexing steps.
When you slice multi dimension of array, if fewer indices are provided than the number of axes, the missing indices are considered complete slices. Hence, when you are essentially doing when calling x[:][1]
is x[:,:][1,:]
Therefore, x[:,:]
will just return x itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With