scipy Numpy:行唯一元素

bvuwiixz  于 2022-11-09  发布在  其他
关注(0)|答案(5)|浏览(172)

是否有人知道如何在矩阵中逐行获取唯一元素?例如,输入矩阵可能如下所示:

a = [[1,2,1,3,4,1,3],
     [5,5,3,1,5,1,2],
     [1,2,3,4,5,6,7],
     [9,3,8,2,9,8,4],
     [4,6,7,4,2,3,5]]

它应返回以下内容:

b = rowWiseUnique(a)
=>  b = [[1,2,3,4,0,0,0],
       [5,3,1,2,0,0,0],
       [1,2,3,4,5,6,7],
       [9,3,8,2,4,0,0],
       [4,6,7,2,3,5,0]]

在numpy中做这件事最有效的方法是什么?我试过下面的代码,有没有更好更短的方法来做这件事?

import numpy as np
def uniqueRowElements(row):
    length = row.shape[0]
    newRow = np.unique(row)
    zerosNumb = length-newRow.shape[0]
    zeros = np.zeros(zerosNumb)
    nR = np.concatenate((newRow,zeros),axis=0)
    return nR    

b = map(uniqueRowElements,a)
b = np.asarray(b)
print b
afdcj2ne

afdcj2ne1#

假设a中的值是浮点数,您可以用途:

def using_complex(a):
    weight = 1j*np.linspace(0, a.shape[1], a.shape[0], endpoint=False)
    b = a + weight[:, np.newaxis]
    u, ind = np.unique(b, return_index=True)
    b = np.zeros_like(a)
    np.put(b, ind, a.flat[ind])
    return b

In [46]: using_complex(a)
Out[46]: 
array([[1, 2, 0, 3, 4, 0, 0],
       [5, 0, 3, 1, 0, 0, 2],
       [1, 2, 3, 4, 5, 6, 7],
       [9, 3, 8, 2, 0, 0, 4],
       [4, 6, 7, 0, 2, 3, 5]])

请注意,using_complex不会以与rowWiseUnique相同的顺序返回唯一值;根据问题下方的注解,不需要对值进行排序。
最有效的方法可能取决于数组中的行数。如果行数不是太大,使用mapfor-loop分别处理每行的方法是很好的,但是如果有很多行,可以使用numpy技巧通过调用np. unique来处理整个数组,从而做得更好。
诀窍是给每一行添加一个唯一的虚数,这样,当你调用np.unique时,如果原始数组中的浮点数出现在不同的行中,它们将被识别为不同的值,但如果它们出现在同一行中,它们将被视为相同的值。
下面,这个技巧是在函数using_complex中实现的。下面是一个基准测试,将原始方法rowWiseUniqueusing_complexsolve进行比较:
第一个

fgw7neuy

fgw7neuy2#

最快的方法应该是使用sort和diff将所有重复项设置为零:

def row_unique(a):
    unique = np.sort(a)
    duplicates = unique[:,  1:] == unique[:, :-1]
    unique[:, 1:][duplicates] = 0
    return unique

这大约是我电脑上unutbu解决方案的3倍:

In [26]: a = np.random.randint(1, 101, size=100000).reshape(1000, 100)

In [27]: %timeit row_unique(a)
100 loops, best of 3: 3.18 ms per loop

In [28]: %timeit using_complex(a)
100 loops, best of 3: 15.4 ms per loop

In [29]: assert np.all(np.sort(using_complex(a)) == np.sort(row_unique(a)))

为了返回每个唯一元素的计数,还可以执行以下操作:

def row_unique(a, return_counts=False):
    unique = np.sort(a)
    duplicates = unique[:,  1:] == unique[:, :-1]
    unique[:, 1:][duplicates] = 0
    if not return_counts:
        return unique
    count_matrix = np.zeros(a.size, dtype="int")
    idxs = np.flatnonzero(unique)
    counts = np.diff(idxs)
    count_matrix[idxs[:-1]] = counts
    count_matrix[idxs[-1]] = a.size-idxs[-1]
    return unique, count_matrix.reshape(a.shape)

`

svgewumm

svgewumm3#

您可以执行以下操作:

def solve(arr):
    n = arr.shape[1]
    new_arr = np.empty(arr.shape)
    for i, row in enumerate(arr):
        new_row = np.unique(row)
        new_arr[i] = np.hstack((new_row, np.zeros(n - len(new_row))))
    return new_arr

对于1000 X 1000阵列,这比OP的当前代码快大约4倍:

>>> arr = np.arange(1000000).reshape(1000, 1000)
>>> %timeit b = map(uniqueRowElements, arr); b = np.asarray(b)
10 loops, best of 3: 71.2 ms per loop
>>> %timeit solve(arr)
100 loops, best of 3: 16.6 ms per loop
qhhrdooz

qhhrdooz4#

OP解决方案的一个变体,在使用numpy.apply_along_axis和大型(1000x1000)阵列时略有改进,大约提高了3%,但仍然比Ashwini的解决方案慢一点。

def foo(row):
    b = np.zeros(row.shape)
    u = np.unique(row)
    b[:u.shape[0]] = u
    return b

b = np.apply_along_axis(foo, 1, a)

使用行中有重复项的数组a = np.random.random_integers(0, 500, (1000*1000)).reshape(1000,1000)时,时序比似乎更接近。

evrscar2

evrscar25#

这不是很有效率,因为将所有的零移到行的末尾不是很有效率。

import numpy as np

a = np.array([[1,2,1,3,4,1,3],
     [5,5,3,1,5,1,2],
     [1,2,3,4,5,6,7],
     [9,3,8,2,9,8,4],
     [4,6,7,4,2,3,5]])

row_len = len(a[0])

for r in xrange(len(a)):
    found = set()
    for i in xrange(row_len):
        if a[r][i] not in found:
            found.add(a[r][i])
        else:
            a[r][i] = 0
    a[r].sort()
    a[r] = a[r][::-1]

print(a)

输出量:

[[4 3 2 1 0 0 0]
 [5 3 2 1 0 0 0]
 [7 6 5 4 3 2 1]
 [9 8 4 3 2 0 0]
 [7 6 5 4 3 2 0]]

相关问题