mahmoud / boltons

🔩 Like builtins, but boltons. 250+ constructs, recipes, and snippets which extend (and rely on nothing but) the Python standard library. Nothing like Michael Bolton.
https://boltons.readthedocs.org
Other
6.47k stars 349 forks source link

numpy multi-dimensional slices? #148

Open kurtbrose opened 6 years ago

kurtbrose commented 6 years ago

numpy multi-dimensional slices can be nice as a standalone capability

use case: given the return of fetchall() from sqlalchemy / DBAPI2 database driver, drop the first column

nslice(rows)[:, 1:]

EDIT: whoops this implementation is garbage

class nslice(object):
    __slots__ = ("obj",)
    def __init__(self, obj): self.obj = obj

    def __getitem__(self, slice):
        if type(slice) is not tuple:
            return self.obj[slice]
        return fslice(self.obj, *slice)

def fslice(obj, *slice):
    if len(slice) == 1:
        return obj[slice[0]]
    return [fslice(e, *slice[1:]) for e in obj][slice[0]]
mahmoud commented 6 years ago

Great idea! I could definitely see subselecting an arbitrary lists of lists out of another lists of lists, sort of like a "crop" tool for two-dimensional sequence-based datasets. Multidimensional gets kind of hard to explain, but might be ok to include if we have the simplified/more-commonly-used variant as a reference alongside it?