I have a numpy array like this:
candidates =
array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,
0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0]])
And I do not understand what is the difference between candidates[0]
:
candidates[0] =
array([1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0]
candidates[0].shape = (34,)
And candidates[0:1]
:
candidates[0:1] =
array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0]])
candidates[0:1].shape = (1, 34)
because I believe the two should give the exact same results? I mean the later i.e. candidates[0:1]
is supposed to represent the first element only, right? So, what is the difference between the two exactly?
Access Array ElementsThe indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
The zeros() function is used to get a new array of given shape and type, filled with zeros. Shape of the new array, e.g., (2, 3) or 2. The desired data-type for the array, e.g., numpy.
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. The elements in a NumPy array are all required to be of the same data type, and thus will be the same size in memory.
Shape[1] is n. shape is a tuple that always gives dimensions of the array. The shape function is a tuple that gives you an arrangement of the number of dimensions in the array.
In Python, [0]
is indexing—it returns the first element, while [0:1]
is slicing—it returns a collection of all of the first 1 elements.
This may be easier to see with a plain old list:
>>> lst = [1, 2, 3]
>>> lst[0]
1
>>> lst[0:1]
[1]
Numpy extends Python indexing and slicing, and some of these would give you a 2D result, for different reasons—e.g., you could index with [0]
as an “array-like”, which would work as an index array), but the relevant basics are the same here. For a 2D numpy array, the elements are rows, so candidates[0]
is the first row—a 1D array, while candidates[0:1]
is an array of all of the first 1 rows—a 2D array. So the first one has shape (34,)
, and the second has shape (1, 34)
.
The difference may not be obvious if you don't look closely, but compare how the two start:
array([1,
array([[1,
They're not lined up, because the second one has two brackets instead of one, which is because it's a 2D array instead of 1D.
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