May I know why ndarray allows floating point index accessing, and what does that mean?
>>> wk1 = numpy.arange(10)
>>> wk1[1:2.8]
array([1])
>>> wk1 = [1,2,3,4,5,6,7,8,9,10]
>>> wk1[1:2.8]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method
>>>
In previous versions the values to be used as array indices could just be left as floats, but now it is necessary to convert them to integers before using them as index values.
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.
In Python 3, division results in a quotient of type, float . However, above we are subscripting a list which requires integer index references. Floats cannot be used as indices.
Data Types in Python integer - used to represent integer numbers. e.g. -1, -2, -3. float - used to represent real numbers. e.g. 1.2, 42.42. boolean - used to represent True or False.
Using a floating point index in an ndarray is no longer allowed and raises an error as of version 1.12.
IndexError: only integers, slices (`:`), ellipsis (`...`),
numpy.newaxis (`None`) and integer or boolean arrays are valid indices
Indexing with floats will raise IndexError, e.g., a[0, 0.0]. (See 1.11 release notes)
Indexing with floats raises IndexError, e.g., a[0, 0.0]. (See 1.12 release notes)
(my emphasis)
This can be useful, and I wonder why other classes don't do it the way numpy does.
One particularly helpful time when I've noticed this is if your numpy array is an image, and you have an event handler for mouse clicks which give you event.xdata
and event.ydata
as floats, then you can still get a region of interest using the slices without having to convert them to pixel coordinates. For example, suppose you were cropping an image or zooming in an image by clicking and dragging a selection - the mouse position in the image will generally be on sub-pixel coordinates except for the special case where the image is displayed 1:1 scale.
As a side note, non-integer slice notation (even complex numbers in slices) can be used in their index tricks classes r_
and c_
, for example:
>>>np.r_[0:3:0.1]
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ,
1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1,
2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9])
>>>np.c_[-1:1:9j]
array([[-1. ],
[-0.75],
[-0.5 ],
[-0.25],
[ 0. ],
[ 0.25],
[ 0.5 ],
[ 0.75],
[ 1. ]])
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