Skip to content Skip to sidebar Skip to footer

Efficient Way To Cast Scalars To Numpy Arrays

When I write a function that accepts ndarray or scalar inputs def foo(a): # does something to `a` # # a: `x` dimensional array or scalar # . . . cast(a, x)

Solution 1:

asarray returns the array itself (if starting with an array):

In [271]: x=np.arange(10)
In [272]: y = np.asarray(x)
In [273]: id(x)
Out[273]: 2812424128
In [274]: id(y)
Out[274]: 2812424128     # same id

ndmin produces a view:

In [276]: y = np.array(x, ndmin=2, copy=False)
In [277]: y
Out[277]: array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
In [278]: id(x)
Out[278]: 2812424128In [279]: id(y)
Out[279]: 2811135704    # different id
In [281]: x.__array_interface__['data']
Out[281]: (188551320, False)
In [282]: y.__array_interface__['data']  # same databuffer
Out[282]: (188551320, False)

ndmin on an array of the right dim already:

In [286]: x = np.arange(9).reshape(3,3)
In [287]: y = np.array(x, ndmin=2, copy=False)
In [288]: id(x)
Out[288]: 2810813120
In [289]: id(y)
Out[289]: 2810813120     # same id

Similar discussion with astype,

confused about the `copy` attribution of `numpy.astype`

Post a Comment for "Efficient Way To Cast Scalars To Numpy Arrays"