Python 2D NumPy array comprehension -
i new numpy. have 2-d numpy array containing floating point values. wish index of elements greater 70 % of value, t ,in entire matrix.
output = [(1,2),(4,7),(7,1)]
meaning arr[1][2], arr[4][7] , arr[7][1] have values greater 70% of t
using 2 loops job done uncomplicated way. pythonic way of getting done (list comprehension etc.) ? please point out duplicates. !
an example:
in [76]: arr=np.arange(20, dtype=float).reshape(4,5) in [77]: arr out[77]: array([[ 0., 1., 2., 3., 4.], [ 5., 6., 7., 8., 9.], [ 10., 11., 12., 13., 14.], [ 15., 16., 17., 18., 19.]])
a boolean index can select values array
in [79]: arr>15 out[79]: array([[false, false, false, false, false], [false, false, false, false, false], [false, false, false, false, false], [false, true, true, true, true]], dtype=bool) in [80]: arr[arr>15] out[80]: array([ 16., 17., 18., 19.])
indexes condition true, can used select elements
in [81]: i=np.nonzero(arr>15) in [82]: out[82]: (array([3, 3, 3, 3], dtype=int32), array([1, 2, 3, 4], dtype=int32)) in [83]: arr[i] out[83]: array([ 16., 17., 18., 19.])
or turn index tuple list of pairs
in [84]: list(zip(*i)) out[84]: [(3, 1), (3, 2), (3, 3), (3, 4)] in [87]: [arr[j] j in zip(*i)] out[87]: [16.0, 17.0, 18.0, 19.0]
Comments
Post a Comment