What is a more Pythonic way of doing this?
min_odds = np.arange( 1.05, 2.0, 0.01 )
min_odds = min_odds.reshape( len( min_ods ), -1 )
The code creates an ndarray of shape (95,) and converts it to shape (95,1).
Also, why does numpy sometimes create arrays of size (95,) with a blank last dimension?
I often follow arange
with a reshape
to generate test arrays, e.g.
np.arange(12).reshape(3,4)
Use -1
to avoid taking len()
, e.g.
np.arange(10).reshape(-1,1).shape # (10, 1)
arange
always returns a 1d array. numpy
arrays can have any number of dimensions, including 0. Shape is expressed as a tuple. (10,)
is just a 1 term tuple. (the , is needed to distinguish it from (10)
).
You can slice with np.newaxis
(which is just an fancy alias for None
) if you'd like:
>>> np.arange( 1.05, 2.0, 0.01 )[:,np.newaxis].shape
(95, 1)
If you prefer what you've got, I'd get rid of the -1
and just use 1
(unless you want your users to have to look up what the -1
is supposed to mean like I just did...).
>>> arr = np.arange( 1.05, 2.0, 0.01 )
>>> arr = arr.reshape(len(arr), 1)
>>> arr.shape
(95, 1)
As for your second question,
"why does numpy sometimes create arrays of size (95,) with a blank last dimension?"
I'm not 100% sure I understand what you're asking. ndarray.shape
is a tuple
. A tuple with a single element's string representation looks like (something,)
.
Also note the comments below about preferring np.linspace
to np.arange
in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With