有沒有一種直接的方法可以根據標準選擇最近的鄰居?例如,T1產量array([0.04, 0.16, 0.39])。現在我想掃描 0.04 即 0.55 和 0.23 的最近鄰居。它選擇 0.23,因為它符合標準 (0.23<0.5)。現在它掃描 0.85 和 0.43 并選擇 0.43<0.5 等等......
import numpy as np
P1 = np.array([[0.04, 0.55, 0.16, 0.39, 0.51],
[0.23, 0.85, 0.73, 0.53, 0.11],
[0.43, 0.26, 0.1 , 0.06, 0.88],
[0.95, 0.27, 0.61, 0. , 0.17],
[0.01, 0.72, 0.87, 0.14, 0.06]])
P2=0.5
T=P1[0,:]
T1=T[P2>T]
print([T1])
所需的輸出是
array([[0.04,0.23,0.43,0.26,0.1,0.27,0.06,0,0.17,0.14,0.06]])
uj5u.com熱心網友回復:
好的,我在這里解決的是
“給定陣列中的初始位置(i,j)- 迭代掃描最近鄰(相對于當前)元素,如果滿足特定條件 - 重復一個新元素。”
import numpy as np
def get_neighbor_indices(position, dimensions):
'''
dimensions is a shape of np.array
'''
i, j = position
indices = [(i 1,j), (i-1,j), (i,j 1), (i,j-1)]
return [
(i,j) for i,j in indices
if i>=0 and i<dimensions[0]
and j>=0 and j<dimensions[1]
]
def iterate_array(init_i, init_j, arr, condition_func):
'''
arr is an instance of np.array
condition_func is a function (value) => boolean
'''
indices_to_check = [(init_i,init_j)]
checked_indices = set()
result = []
while indices_to_check:
pos = indices_to_check.pop()
if pos in checked_indices:
continue
item = arr[pos]
checked_indices.add(pos)
if condition_func(item):
result.append(item)
indices_to_check.extend(
get_neighbor_indices(pos, arr.shape)
)
return result
P1 = np.array([[0.04, 0.55, 0.16, 0.39, 0.51],
[0.23, 0.85, 0.73, 0.53, 0.11],
[0.43, 0.26, 0.1 , 0.06, 0.88],
[0.95, 0.27, 0.61, 0. , 0.17],
[0.01, 0.72, 0.87, 0.14, 0.06]])
iterate_array(0,0, P1, lambda x : x < 0.5)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436239.html
下一篇:這是什么python語法?
