numpy对二维数组去重(附np.unique()文档)

首先放上一个链接:如何使用python将二维数组去重呢?

其中提到了两种方案:

#方案1:转化为虚数
x=c[:,0]+c[:,1]*1j
print('转化为虚数:',x)
print('虚数去重后:',np.unique(x))
print(np.unique(x,return_index=True))#return_index:输出的元素索引值
idx=np.unique(x,return_index=True)[1]
print('二维数组去重:\n',c[idx])

#方案2:利用set
print('去重方案2:\n',np.array(list(set([tuple(t) for t in c]))))

但是思前想后,感觉这么简单常用的功能不至于这么麻烦。于是我又把np.unique()这个函数看了一遍,发现np.unique()是可以直接解决的。PS:吐槽一下,第二种方案是真的慢。

直接上代码:

import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[1,2,3,4]])
print 'a:'
print a
print 'unique:'
print np.unique(a, axis=0)

输出:

a:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [ 1  2  3  4]]
unique:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

我们可以看到,np.unique()并不是简单地只有np.unique(a)这么一种调用形式。附上np.unique()的文档

numpy.unique

numpy.unique(arreturn_index=Falsereturn_inverse=Falsereturn_counts=Falseaxis=None)[source]
Find the unique elements of an array.

Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements: the indices of the input array that give the unique values, the indices of the unique array that reconstruct the input array, and the number of times each unique value comes up in the input array.

Parameters:

ar : array_like

Input array. Unless axis is specified, this will be flattened if it is not already 1-D.

return_index : bool, optional

If True, also return the indices of ar (along the specified axis, if provided, or in the flattened array) that result in the unique array.

return_inverse : bool, optional

If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct ar.

return_counts : bool, optional

If True, also return the number of times each unique item appears in ar. .. versionadded:: 1.9.0

axis : int or None, optional

The axis to operate on. If None, ar will be flattened beforehand. Otherwise, duplicate items will be removed along the provided axis, with all the other axes belonging to the each of the unique elements. Object arrays or structured arrays that contain objects are not supported if the axis kwarg is used. .. versionadded:: 1.13.0

Returns:

unique : ndarray

The sorted unique values.

unique_indices : ndarray, optional

The indices of the first occurrences of the unique values in the original array. Only provided if return_index is True.

unique_inverse : ndarray, optional

The indices to reconstruct the original array from the unique array. Only provided if return_inverse is True.

unique_counts : ndarray, optional

The number of times each of the unique values comes up in the original array. Only provided if return_counts is True. .. versionadded:: 1.9.0

发表评论