delete the first element in subview of a matrix delete the first element in subview of a matrix numpy numpy

delete the first element in subview of a matrix


As requested, a numpy solution:

import numpy as npa = np.array([[0,1], [0,2], [0,3], [0,4], [1,5], [1,6], [1,7], [2,8], [2,9]])_,i = np.unique(a[:,0], return_index=True)b = np.delete(a, i, axis=0)

(above is edited to incorporate @Jaime's solution, here is my original masking solution for posterity's sake)

m = np.ones(len(a), dtype=bool)m[i] = Falseb = a[m]

Interestingly, the mask seems to be faster:

In [225]: def rem_del(a):   .....:     _,i = np.unique(a[:,0], return_index=True)   .....:     return np.delete(a, i, axis = 0)   .....: In [226]: def rem_mask(a):   .....:     _,i = np.unique(a[:,0], return_index=True)   .....:     m = np.ones(len(a), dtype=bool)   .....:     m[i] = False   .....:     return a[m]   .....: In [227]: timeit rem_del(a)10000 loops, best of 3: 181 us per loopIn [228]: timeit rem_mask(a)10000 loops, best of 3: 59 us per loop


Pass in your lists and the key that you want to check values on.

def getsubset(set, index):    hash = {}    for list in set:        if not list[index] in hash:            set.remove(list)            hash[list[index]]  = list    return set


You want to use itertools.groupby() with a dash of itertools.islice() and itertools.chain:

from itertools import islice, chain, groupbyfrom operator import itemgetterlist(chain.from_iterable(islice(group, 1, None)                         for key, group in groupby(inputlist, key=itemgetter(0))))
  • The groupby() call groups the input list into chunks where the first item is the same (itemgetter(0) is the grouping key).
  • The islice(group, 1, None) call turns the groups into iterables where the first element will be skipped.
  • The chain.from_iterable() call takes each islice() result and chains them together into a new iterable, which list() turns back into a list.

Demo:

>>> list(chain.from_iterable(islice(group, 1, None) for key, group in groupby(inputlist, key=itemgetter(0))))[[0, 2], [0, 3], [0, 4], [1, 6], [1, 7], [2, 9]]