如何解决获得两个2d numpy数组的集合差异的热值,或等效于2d数组中的np.setdiff1d的热点?
在Get intersecting rows across two 2D numpy arrays中,他们通过使用函数np.intersect1d
得到了相交的行。因此,我将函数更改为使用np.setdiff1d
来获得设置差异,但是它无法正常工作。以下是代码。
def set_diff2d(A,B):
nrows,ncols = A.shape
dtype={'names':['f{}'.format(i) for i in range(ncols)],'formats':ncols * [A.dtype]}
C = np.setdiff1d(A.view(dtype),B.view(dtype))
return C.view(A.dtype).reshape(-1,ncols)
以下数据用于检查问题:
min_dis=400
Xt = np.arange(50,3950,min_dis)
Yt = np.arange(50,min_dis)
Xt,Yt = np.meshgrid(Xt,Yt)
Xt[::2] += min_dis/2
# This is the super set
turbs_possible_locs = np.vstack([Xt.flatten(),Yt.flatten()]).T
# This is the subset
subset = turbs_possible_locs[np.random.choice(turbs_possible_locs.shape[0],50,replace=False)]
diffs = set_diff2d(turbs_possible_locs,subset)
diffs
应该具有50x2的形状,但不是。
解决方法
好的,要解决您的问题,请尝试以下调整:
def set_diff2d(A,B):
nrows,ncols = A.shape
dtype={'names':['f{}'.format(i) for i in range(ncols)],'formats':ncols * [A.dtype]}
C = np.setdiff1d(A.copy().view(dtype),B.copy().view(dtype))
return C
问题是-应用A
后的.view(...)
被分成两半-因此它有2个tuple
列,而不是B
这样的1列。即应用dtype
的结果是,您实际上将2列折叠到tuple
中-这就是为什么您可以首先在1d中进行交集的原因。
文档后报价:
”
a.view(some_dtype)或a.view(dtype = some_dtype)构造具有不同数据类型的阵列内存视图。这可能导致对内存字节的重新解释。
”
Src https://numpy.org/doc/stable/reference/generated/numpy.ndarray.view.html
我认为“重新解释”正是发生的事情-因此,为了简单起见,我只.copy()
数组。
NB ,但是我不会对它进行平方运算-总是A
被“破坏”-无论是分配还是内联B
总是可以的...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。