Skip to content

Instantly share code, notes, and snippets.

@alexland
Last active August 29, 2015 14:11
Show Gist options
  • Save alexland/0aba0eb3e7341afa19e0 to your computer and use it in GitHub Desktop.
Save alexland/0aba0eb3e7341afa19e0 to your computer and use it in GitHub Desktop.
in-place merge two halves of an array w/ specified offset
>>> data = NP.arange(20)
>>> data
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
# use floor division to account for an odd number of items in the array,
# ie, 20//2 and 21//2 return the *same* result
>>> mp = data.shape[0] // 2
'''
note that slicing does not copy
eg, this quote from the NumPy docs:
"[s]licing operation creates a view on the original array,
which is just a way of accessing array data.
Thus the original array is not copied in memory"
source: (http://scipy-lectures.github.io/intro/numpy/numpy.html#indexing-and-slicing)
note also that these two slices (passed in as arguments to 'zip' are
*not* modified by zip; the python docs are explicit that zip does
create an additional container from the zipped items passed to it;
what's more, in python3, zip returns an iterator (not a list),
so 'izip' was removed from itertools library because its functionality
was now completedly subsumed by 'zip'
'''
# split the array into two halves, on the midpoint
>>> d1 = data[:mp]
>>> d2 = data[mp:]
# zip the two pieces together & flatten the result above
# pretty sure this is the most efficient way to do this in python
>>> data0 = [itm for t in zip(data[:mp], data[mp:]) for itm in t]
# alternatively, i could just call numpy's ravel method to get the same result
>>> data0
[0, 10, 1, 11, 2, 12, 3, 13, 4, 14, 5, 15, 6, 16, 7, 17, 8, 18, 9, 19]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment