gpt4 book ai didi

python - 如何使用 python 在两个数组中找到匹配的数据点并返回第三个?

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:16 24 4
gpt4 key购买 nike

我是 python 的新手,正在尝试从另外 2 个数组创建第 3 个数组。我有两个变量(X 和 Y)都与深度相关,但不在完全相同的深度点上。我想遍历与 X 关联的深度值,并在数组 Y 中找到深度在 X 的 50 厘米以内的深度值。然后在第三个数组中返回深度和 Y 值。

我认为“for”循环可以做到这一点,但我不知道怎么做。

代码:

A = np.genfromtxt('file.txt', names=True)
B = np.genfromtxt('file2.txt', names=True)

Depth1 = A['Depth']
X = A['variable1']

Depth2 = B['Depth']
Y = B['number']

A包含806行,B包含456行。

我想过滤 A 并提取对应于 B 中每个深度点 50 厘米以内的值(深度和 X),最好是提取到另一个数组中。

我该怎么做?我发现在网上搜索的东西包含带有 for 循环的列表,但不包含数组。

示例数据:

A = [(0.6, 1.463) (0.95, 1.468) (1.7, 1.465) (2.5, 1.502) (265.38, 1.715) ... (Depth1, X)]
B = [(0.58, 0.726) (0.93, 0.688) (1.69, 0.713) (2.48, 0.606) ... (Depth2, Y)]

示例输出:

C = [(0.58, 1.463) (0.93, 1.468) (1.69, 1.465) ... (Depth2, X)]

最佳答案

depths = [a[(i-50. <= a) & (a <= i+50.)] for i in b]

编辑:作为对评论的回应,事实并非如此。 ab是 numpy.arrays; i-50. < a评估为标志数组,带有 1在每个值 > i-50 的位置,然后是 a[flagarray]仅返回标志数组包含 1 的条目。 &结合两个标志数组,以便只提取感兴趣的值。希望对您有所帮助。

Edit2:类似

result = []
for i,n in zip(depth2,y):
mask = (i-50. <= a) & (a <= i+50.)
result.append((n, depth1[mask], x[mask]))

Edit3:看起来,对于每个 B 深度,您需要一个值 - 最近的对应 A 深度的标签?

import numpy as np

a = np.array([[0.6, 1.463], [0.95, 1.468], [1.7, 1.465], [2.5, 1.502], [265.38, 1.715]])
b = np.array([[0.58, 0.726], [0.93, 0.688], [1.69, 0.713], [2.48, 0.606]])

d1 = a[:,0]
x = a[:,1]

d2 = b[:,0]
y = b[:,1]

def find_index_of_nearest_value(array, value):
return np.abs(array - value).argmin()

c = [(d, x[find_index_of_nearest_value(d1, d)]) for d,y in b]

结果

[(0.58, 1.463), (0.93, 1.468), (1.69, 1.465), (2.48, 1.502)]

这可以通过对深度数组进行排序并按升序遍历它们来加快速度 - 但对于少于 1000 个值,这应该足够快了。

关于python - 如何使用 python 在两个数组中找到匹配的数据点并返回第三个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11319693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com