# triggers a copy due to transpose
c = a.T.reshape((1, -1))
# does not trigger a copy
b = a.reshape((1, -1))
- flatten always returns a copy. Use ravel, when possible
# flatten
d = a.flatten()
e = a.ravel()
- Use broadcasting instead of np.tile
- Fancy indexing yields a copy
b1 = a[::10] # array view: does not yield a copy, takes 804 ns per loop
b2 = a[np.arange(0, n, 10)] # fancy indexing: creates a copy, takes 14.1 ms per loop
- Logical indexing can be done using np.compress, which is faster than fancy indexing
i = np.random.random_sample(n) < .5
b1 = a[i] # fancy indexing: 59.8 ms per loop
b2 = np.compress(i, a, axis=0) # takes 24.1 ms per loop
- Use np.take as alternative to fancy indexing, when possible
i = np.arange(0, n, 10)
b1 = a[i] # 13 ms per loop
b2 = np.take(a, i, axis=0) # 4.87 ms per loop
1 comment
[ 5.1 ms ] story [ 18.4 ms ] thread- Avoid implicit copy operations
- Reshaping involves a copy when also transposing - flatten always returns a copy. Use ravel, when possible - Use broadcasting instead of np.tile- Fancy indexing yields a copy
- Logical indexing can be done using np.compress, which is faster than fancy indexing - Use np.take as alternative to fancy indexing, when possible