Coordinates of numpy array from index and shape

From , 3 Years ago, written in Python, viewed 215 times.
URL https://pastebin.vip/view/fbb17c69
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Fri Oct 05 13:32:06 2012
  4.  
  5. @author: Garrett Berg
  6. """
  7. import numpy as np
  8. import itertools
  9. import math
  10.  
  11. def index_to_coords(index, shape):
  12.     '''convert index to coordinates given the shape'''
  13.     coords = []
  14.     for i in xrange(1, len(shape)):
  15.         divisor = int(np.product(shape[i:]))
  16.         value = index//divisor
  17.         coords.append(value)
  18.         index -= value * divisor
  19.     coords.append(index)
  20.     return tuple(coords)
  21.    
  22. def first_coords_et(data_matrix, value, start = 0):
  23.     '''the first coordinates that are equal to the value'''
  24.     index = first_index_et(data_matrix.flatten(), value, start)
  25.     shape = data_matrix.shape
  26.     return index_to_coords(index, shape)
  27.  
  28. def first_index_et(data_list, value, start = 0):
  29.     data_list = itertools.islice(data_list, start, None)
  30.     '''same as data_list.index(value), except with exception handling
  31.    Also finds 'nan' values and works with numpy arrays -- quickly!'''
  32.     try:
  33.         if type(value) == float and math.isnan(value):
  34.             floats = (float, np.float64, np.float32, np.float96)
  35.             isnan = math.isnan
  36.             return next(data[0] for data in enumerate(data_list)
  37.               if (type(data[1]) in floats
  38.               and isnan(data[1])))  + start
  39.         else:
  40.             return next(data[0] for data in
  41.             enumerate(data_list) if data[1] == value) + start
  42.     except (ValueError, StopIteration): return - 1
  43.  
  44. if __name__ == '__main__':
  45.     ab = np.arange(0, 30000)
  46.     ab.shape = (20, 20, 30000/(20*20))
  47.     value = ab[7][12][0]
  48.     print first_coords_et(ab, value)
  49.     # (7, 12, 0)
  50. #//python/5534

Reply to "Coordinates of numpy array from index and shape"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website