小编Gen*_*sky的帖子

查找两个numpy数组之间的绝对最小值,但保持符号

考虑两个不同长度的数组:

A = np.array([58, 22, 86, 37, 64])

B = np.array([105, 212,   5, 311, 253, 419, 123, 461, 256, 464])
Run Code Online (Sandbox Code Playgroud)

对于in中的每个值A,我想找到in A和中的值之间的最小绝对差B。我Pandas之所以使用,是因为我的实际数组是Pandas数据帧的子集,而且因为该apply方法是一种方便(尽管很慢)的方法来处理两个不同大小的数组之间的差异:

In [22]: pd.Series(A).apply(lambda x: np.min(np.abs(x-B)))
Out[22]:
0    47
1    17
2    19
3    32
4    41
dtype: int64
Run Code Online (Sandbox Code Playgroud)

但是我也想保留符号,所以期望的输出是:

0    -47
1     17
2    -19
3     32
4    -41
dtype: int64
Run Code Online (Sandbox Code Playgroud)

[更新]我的实际数组AB长度大约为5e4和1e6,因此低内存解决方案将是理想的。另外,我希望避免使用Pandas,因为它在实际阵列上非常慢。

python numpy pandas difference

3
推荐指数
1
解决办法
124
查看次数

标签 统计

difference ×1

numpy ×1

pandas ×1

python ×1