我有两个numpy数组,我想从第一个数组中删除重复值(包括原始值),并删除第二个数组中匹配位置的项目。
例如:
a = [1, 2, 2, 3]
b = ['a', 'd', 'f', 'c']
Becomes:
a = [1, 3]
b = ['a', 'c']
我需要高效地完成这项任务,而不是使用费时的幼稚解决方案。
这里有一个与 np.unique
相关的例子 -
unq,idx,c = np.unique(a, return_index=True, return_counts=True)
unq_idx = np.sort(idx[c==1])
a_out = a[unq_idx]
b_out = b[unq_idx]
示例运行:
In [34]: a
Out[34]: array([1, 2, 2, 3])
In [35]: b
Out[35]: array(['a', 'd', 'f', 'c'], dtype='|S1')
In [36]: unq,idx,c = np.unique(a, return_index=1, return_counts=1)
...: unq_idx = idx[c==1]
...: a_out = a[unq_idx]
...: b_out = b[unq_idx]
In [37]: a_out
Out[37]: array([1, 3])
In [38]: b_out
Out[38]: array(['a', 'c'], dtype='|S1')
既然你已经接触过NumPy,那么你可能想考虑一下Pandas,它在内部使用了NumPy:
import pandas as pd
a = pd.Series([1, 2, 2, 3])
b = pd.Series(['a', 'd', 'f', 'c'])
flags = ~a.duplicated(keep=False)
idx = flags[flags].index
a = a[idx].values
b = b[idx].values
结果:
print(a, b, sep='\n')
array([1, 3], dtype=int64)
array(['a', 'c'], dtype=object)
np.sort
很令人沮丧。有没有一种方法可以保持 O(n) 的复杂度? - jpp