Created
October 20, 2020 17:48
-
-
Save radugrosu/0622efc4d8eb5c63fa2181de0f076852 to your computer and use it in GitHub Desktop.
named array proof of concept
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from typing import Sequence | |
class NamedArray(np.ndarray): | |
def __new__(cls, array: np.ndarray, names: Sequence[str]): | |
assert array.shape[-1] == len(names) | |
obj = np.asarray(array).view(cls) | |
obj.names = names | |
obj._lookup = dict(zip(names, range(len(array)))) | |
return obj | |
def __array_finalize__(self, obj): | |
if obj is None: | |
return | |
self.names = getattr(obj, 'names', None) | |
def __getitem__(self, item): | |
if isinstance(item, str): | |
item = self._lookup[item] | |
if isinstance(item, slice): | |
if isinstance(item.start, str): | |
item = slice(self._lookup.get(item.start), | |
self._lookup.get(item.stop), | |
self._lookup.get(item.step)) | |
return super().__getitem__(item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment