Returns the first n_desired items of an array
(array, n_desired)
| 75 | |
| 76 | |
| 77 | def first_n_items(array, n_desired): |
| 78 | """Returns the first n_desired items of an array""" |
| 79 | # Unfortunately, we can't just do array.flat[:n_desired] here because it |
| 80 | # might not be a numpy.ndarray. Moreover, access to elements of the array |
| 81 | # could be very expensive (e.g. if it's only available over DAP), so go out |
| 82 | # of our way to get them in a single call to __getitem__ using only slices. |
| 83 | from xarray.core.variable import Variable |
| 84 | |
| 85 | if n_desired < 1: |
| 86 | raise ValueError("must request at least one item") |
| 87 | |
| 88 | if array.size == 0: |
| 89 | # work around for https://github.com/numpy/numpy/issues/5195 |
| 90 | return [] |
| 91 | |
| 92 | if n_desired < array.size: |
| 93 | indexer = _get_indexer_at_least_n_items(array.shape, n_desired, from_end=False) |
| 94 | if isinstance(array, ExplicitlyIndexed): |
| 95 | indexer = BasicIndexer(indexer) |
| 96 | array = array[indexer] |
| 97 | |
| 98 | # We pass variable objects in to handle indexing |
| 99 | # with indexer above. It would not work with our |
| 100 | # lazy indexing classes at the moment, so we cannot |
| 101 | # pass Variable._data |
| 102 | if isinstance(array, Variable): |
| 103 | array = array._data |
| 104 | return ravel(to_duck_array(array))[:n_desired] |
| 105 | |
| 106 | |
| 107 | def last_n_items(array, n_desired): |
no test coverage detected
searching dependent graphs…