I want to generate a numpy array of the form:
0.5*[[0, 0], [1, 1], [2, 2], ...]
I want the final array to have a
Here is my attempt:
>>> import numpy as np >>> N = 5 >>> x = np.array(np.repeat(0.5*np.arange(N), 2), np.float32) >>> x array([ 0. , 0. , 0.5, 0.5, 1. , 1. , 1.5, 1.5, 2. , 2. ], dtype=float32)
Is this a good way? Can I avoid the copy (if it is indeed copying) just for type conversion?
You only has to reshape your final result to obtain what you want:
x = x.reshape(-1, 2)
But you could also run
arange passing the
x = np.repeat(0.5*np.arange(N, dtype=np.float32), 2).reshape(-1, 2)
You can easily cast the array as another type using the
astype method, which accepts an argument
But, as explained in the documentation,
numpy checks for some requirements in order to return the view. If those requirements are not satisfied a copy is returned.
You can check if a given array is a copy or a view from another by checking the
OWNDATA attribute accessible through the
flags property of the
EDIT: more on checking if a given array is a copy...
- Is there a way to check if numpy arrays share the same data?