Мы хотим, чтобы найти строки, которые не дублируются в массиве, сохраняя при этом порядок.
Я использую это solution, чтобы объединить каждую строку a
в один элемент, чтобы мы могли найти уникальные строки, используя np.unique(,return_index=True, return_inverse= True)
. Затем я изменил это значение function, чтобы вывести счетчики уникальных строк, используя индекс и инверсию. Оттуда я могу выбрать все уникальные строки, которые имеют counts == 1
.
a = np.array([[1, 2, 3],
[2, 3, 4],
[1, 2, 3],
[3, 2, 1],
[3, 4, 5]])
#use a flexible data type, np.void, to combine the columns of `a`
#size of np.void is the number of bytes for an element in `a` multiplied by number of columns
b = a.view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))
_, index, inv = np.unique(b, return_index = True, return_inverse = True)
def return_counts(index, inv):
count = np.zeros(len(index), np.int)
np.add.at(count, inv, 1)
return count
counts = return_counts(index, inv)
#if you want the indices to discard replace with: counts[i] > 1
index_keep = [i for i, j in enumerate(index) if counts[i] == 1]
>>>a[index_keep]
array([[2, 3, 4],
[3, 2, 1],
[3, 4, 5]])
#if you don't need the indices and just want the array returned while preserving the order
a_unique = np.vstack(a[idx] for i, idx in enumerate(index) if counts[i] == 1])
>>>a_unique
array([[2, 3, 4],
[3, 2, 1],
[3, 4, 5]])
Для np.version> = 1,9
b = a.view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))
_, index, counts = np.unique(b, return_index = True, return_counts = True)
index_keep = [i for i, j in enumerate(index) if counts[i] == 1]
>>>a[index_keep]
array([[2, 3, 4],
[3, 2, 1],
[3, 4, 5]])
Вы можете подсчитать, сколько раз каждая строка появляется с помощью методов, предложенных, например, [ здесь] (http://stackoverflow.com/q/27000092/3923281) и [здесь] (http://stackoverflow.com/q/33786245/3923281). Я думаю, что именно здесь сводится ваша проблема. –
@ajcr Я не могу использовать 'return_counts', поэтому # 1 для меня. К сожалению, для # 2 требуется отсортированный массив, и мне нужно сохранить порядок. – codedog
@codedog Были ли ответы полезными? Если нет, не могли бы вы сообщить нам, что еще вы ищете, – imp9