python - Dynamically adding elements to a NumPy array of unknown final length -
i want create large vector of numbers, length of vector not known. however, give maximum length (which around 100k), although list around 10k. essentially, have loop, within keep adding numbers vector, until criterion met.
my first attempt @ doing python lists, used following:
x = [] in range(k): y = get_list_of_numbers() x += y however, want convert list numpy array, further processing. if using a = np.array(x), takes long time create array.
so, second solution create empty numpy array beginning, , add elements go along:
x = np.empty([]) in range(k): y = get_list_of_numbers() np.append(x, y) however, here np.append(x, y) takes long time process.
so, both solutions slow. there quicker solution out there?
the remaining solution can think of create huge numpy array @ maximum length, , insert each element appropriate slot in array. however, memory inefficient, not have estimate of maximum vector length...
thanks!
if define:
def get_list_of_numbers(): n = np.random.randint(0,10) return list(range(n)) def foo(k): x=[] in range(k): y = get_list_of_numbers() x.extend(y) return x simply calling get_list_of_numbers takes time. turning result array doesn't take time:
in [69]: timeit foo(1000) 100 loops, best of 3: 5.9 ms per loop in [70]: timeit np.array(foo(1000)) 100 loops, best of 3: 6.38 ms per loop in [73]: timeit -n1000 get_list_of_numbers() 1000 loops, best of 3: 6.04 µs per loop lets try preallocation approach:
def foo1(k): x = np.zeros(k*10,int) cnt = 0 in range(k): y = get_list_of_numbers() n = len(y) x[cnt:cnt+n] = y cnt += n x = x[:cnt] return x in [80]: timeit foo1(1000) 100 loops, best of 3: 10.1 ms per loop the array concatenation approach
in [48]: def foo1(k): ...: x = np.zeros(0,int) ...: in range(k): ...: y = get_list_of_numbers() ...: x = np.concatenate((x, y), axis=0) ...: return x in [51]: timeit foo1(1000).shape 100 loops, best of 3: 15.9 ms per loop
Comments
Post a Comment