Returns the last n_desired items of an array
(array, n_desired)
| 105 | |
| 106 | |
| 107 | def last_n_items(array, n_desired): |
| 108 | """Returns the last n_desired items of an array""" |
| 109 | # Unfortunately, we can't just do array.flat[-n_desired:] here because it |
| 110 | # might not be a numpy.ndarray. Moreover, access to elements of the array |
| 111 | # could be very expensive (e.g. if it's only available over DAP), so go out |
| 112 | # of our way to get them in a single call to __getitem__ using only slices. |
| 113 | from xarray.core.variable import Variable |
| 114 | |
| 115 | if (n_desired == 0) or (array.size == 0): |
| 116 | return [] |
| 117 | |
| 118 | if n_desired < array.size: |
| 119 | indexer = _get_indexer_at_least_n_items(array.shape, n_desired, from_end=True) |
| 120 | if isinstance(array, ExplicitlyIndexed): |
| 121 | indexer = BasicIndexer(indexer) |
| 122 | array = array[indexer] |
| 123 | |
| 124 | # We pass variable objects in to handle indexing |
| 125 | # with indexer above. It would not work with our |
| 126 | # lazy indexing classes at the moment, so we cannot |
| 127 | # pass Variable._data |
| 128 | if isinstance(array, Variable): |
| 129 | array = array._data |
| 130 | return ravel(to_duck_array(array))[-n_desired:] |
| 131 | |
| 132 | |
| 133 | def last_item(array): |
no test coverage detected
searching dependent graphs…