Best practice to reduce memory usage while splitting an array
I have an array that I want to split in two halves. Due to symmetry, I'm only interested in keeping the left half of the array.
I can split the array in half by saying:
[a,b] = numpy.split(c,2)
where c is also an array.
Is there a way to return array 'a' or alternatively remove array "b" from memory immediately after splitting the array?
You can copy the first half with
a = x[len(x)//2:].copy()
this would allocate a copy and move the content (thus temporarily takes 1.5 times more memory)
Otherwise, you can just say
a = x[len(x)//2:]
to get a reference to the first half, but the other part will not be removed from memory
You can use delete for this purpose . This is an example:
array=np.array([1,2,3,4])
x=len(array)/2
first_h=np.delete(array,array[x-1:]) #second half
Demo:
>>>print first_h
>>>[1,2]
I'm not sure, but I think it might be better because it relies on the implementation list
( docs ) and I'm sure everything was correct:
>>> r = range(10)
>>> r
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del r[5:]
>>> r
[0, 1, 2, 3, 4]
See also the del statement for lists .