如何简化 numpy 条件语句以查找给定值的元素的相邻索引?
How to simplify numpy conditional statements to find neighbouring indices of elements given a value?
如何简化 numpy 数组中的条件语句以在给定搜索列表 bin 的情况下查找所有列表元素 V 的相邻索引。例如,如果 bins 是 100 个元素的列表,范围从 1.1 到 100.1,则 V 是 [23,77.4,42] 的列表。任务是针对 V 中的每个元素,在 bin 中找到其相邻索引。目前下面的代码需要比较两个向量 4 次,然后将结果添加到输出列表中。如何简化这个任务?
def testFindBoundaryVector():
bins = np.linspace(start=1.1, stop=100.1, num=100)
V = np.array([23, 77.4, 42])
V_T = np.reshape(V, (V.shape[0], 1))
# broadcasting
Diff = np.abs(bins - V_T)
Index = np.argmin(Diff, axis=1)
print(f"indices: {Index}")
print(f"value: {bins[Index]}")
print(f"shape of Diff: {Diff.shape}")
left, right = [], []
LeftIndex = Index[V >= bins[Index]]
RightIndex = LeftIndex + 1
left.extend(LeftIndex)
right.extend(RightIndex)
LeftIndex = Index[V < bins[Index]] - 1
RightIndex = LeftIndex + 1
left.extend(LeftIndex)
right.extend(RightIndex)
print(f"left Index: {left}")
print(f"right Index: {right}")
return
预期结果:
左 = [21,76,40]
右 = [22,77,41]
也许是这样?
import numpy as np
L = np.linspace(1.1, 100.1, 100)
V = np.array([23,77.4,42])
Right = np.argmin(L[:,None]<V[None,:],axis=0)
Left = Right - 1
如何简化 numpy 数组中的条件语句以在给定搜索列表 bin 的情况下查找所有列表元素 V 的相邻索引。例如,如果 bins 是 100 个元素的列表,范围从 1.1 到 100.1,则 V 是 [23,77.4,42] 的列表。任务是针对 V 中的每个元素,在 bin 中找到其相邻索引。目前下面的代码需要比较两个向量 4 次,然后将结果添加到输出列表中。如何简化这个任务?
def testFindBoundaryVector():
bins = np.linspace(start=1.1, stop=100.1, num=100)
V = np.array([23, 77.4, 42])
V_T = np.reshape(V, (V.shape[0], 1))
# broadcasting
Diff = np.abs(bins - V_T)
Index = np.argmin(Diff, axis=1)
print(f"indices: {Index}")
print(f"value: {bins[Index]}")
print(f"shape of Diff: {Diff.shape}")
left, right = [], []
LeftIndex = Index[V >= bins[Index]]
RightIndex = LeftIndex + 1
left.extend(LeftIndex)
right.extend(RightIndex)
LeftIndex = Index[V < bins[Index]] - 1
RightIndex = LeftIndex + 1
left.extend(LeftIndex)
right.extend(RightIndex)
print(f"left Index: {left}")
print(f"right Index: {right}")
return
预期结果: 左 = [21,76,40] 右 = [22,77,41]
也许是这样?
import numpy as np
L = np.linspace(1.1, 100.1, 100)
V = np.array([23,77.4,42])
Right = np.argmin(L[:,None]<V[None,:],axis=0)
Left = Right - 1