np.where()排除数据,其中坐标过于接近

2024-04-27 09:46:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个星团上做光圈测光,为了更容易检测到背景信号,我只想看比n像素(在我的例子中n=16)更远的恒星。 我有两个数组,xs和ys,它们的x和y值是所有恒星的坐标: 使用np.哪里我应该找到所有恒星的指数,其中到所有其他恒星的距离是>;=n

到目前为止,我的方法是一个for循环

import numpy as np

# Lists of coordinates w. values between 0 and 2000 for 5000 stars

xs = np.random.rand(5000)*2000
ys = np.random.rand(5000)*2000

# for-loop, wherein the np.where statement in  question is situated
n = 16
for i in range(len(xs)):
    index = np.where( np.sqrt( pow(xs[i] - xs,2) + pow(ys[i] - ys,2)) >= n)

由于恒星聚在一起非常紧密,我预计数据会严重减少,尽管即使我尝试n=1000,我仍然有大约4000个数据点


Tags: 数据infor信号nprandom像素where
3条回答
np.random.seed(seed=1)
xs = np.random.rand(5000,1)*2000
ys = np.random.rand(5000,1)*2000

n = 16

mask = (xs>=0)

for i in range(len(xs)):
    if mask[i]:
        index = np.where( np.sqrt( pow(xs[i] - x,2) + pow(ys[i] - y,2)) <= n)
        mask[index] = False
        mask[i] = True

x = xs[mask]
y = ys[mask]

print(len(x))

4220

只使用numpy(和部分答案here

X = np.random.rand(5000,2) * 2000
XX = np.einsum('ij, ij ->i', X, X)
D_squared = XX[:, None] + XX - 2 * X.dot(X.T)
out = np.where(D_squared.min(axis = 0) > n**2)

使用scipy.spatial.pdist

from scipy.spatial import pdist, squareform
D_squared = squareform(pdist(x, metric = 'sqeuclidean'))
out = np.where(D_squared.min(axis = 0) > n**2)

使用KDTree实现最大速度:

from scipy.spatial import KDTree

X_tree = KDTree(X)
in_radius = np.array(list(X_tree.query_pairs(n))).flatten()
out = np.where(~np.in1d(np.arange(X.shape[0]), in_radius))

您可以使用np.subtract.outer来创建成对比较。然后检查每一行的距离是否正好有一项小于16(这是与特定开始本身的比较):

distances = np.sqrt(
    np.subtract.outer(xs, xs)**2
    + np.subtract.outer(ys, ys)**2
)
indices = np.nonzero(np.sum(distances < 16, axis=1) == 1)

相关问题 更多 >