python - Identify offset of a value in numpy -
given flatten nxn array in numpy, i'd find minimum value, , offset in array. i've managed find minimum value, possible identify offset (which row , column)?
in example below, = 0.5, how can know if 0.5 [1,0], or [2,1]?
from numpy import * value = 0 num_node = 5 edge = array(zeros((num_node, num_node))) edge = [[ 0., 0., 0., 0., 0. ], [ 0.5, 0., 0., 0., 0. ], [ 1., 0.5, 0., 0., 0. ], [ 1.41421356, 1.11803399, 1., 0., 0. ], [ 1., 1.11803399, 1.41421356, 1., 0. ]] = reshape(edge, num_node*num_node) print min(filter(lambda x : x > value, a))
you use np.where
:
>>> edge = np.array(edge) >>> edge[edge > 0].min() 0.5 >>> np.where(edge == edge[edge > 0].min()) (array([1, 2]), array([0, 1]))
which gives x
coordinates , y
coordinates hit minimum value separately. if want combine them, there lots of ways, e.g.
>>> np.array(np.where(edge == edge[edge > 0].min())).t array([[1, 0], [2, 1]])
a few asides: from numpy import *
bad habit because replaces built-in functions numpy's versions work differently, , in cases have opposite results; allcaps variable names given constants; , your
edge = array(zeros((num_node, num_node)))
line doesn't anything, because edge = [[ 0., ... etc
line makes new list
, binds edge instead. made array , threw away. there's no need call array
here; zeros
returns array.
Comments
Post a Comment