You can create numpy arrays in a bunch of ways. To create an array of empty values
I use np.empty(shape)
where shape is the dimensions of the array to be created:
Using this you have to be careful that all the values will be initialized, or you
might get weird behaviours. The same process can be used to get an array of zeros or
ones. Simply use np.ones(shape)
and np.zeros(shape)
. There are also the commands
np.ones_like(array)
, np.zeros_like(array)
and np.empty_like(array)
which use the
template array define the dimensions:
But if I want to fill an array with a value other than 1 or 0? There are lots of options, I could do something like this:
where I create an array of ones and then multiply each value by my desired initial value. Or I could create an array of the right shape and then assign all of the values at once using slice notation:
This is nice because it is explicit, and makes sense without any other docs. The final
method is to use fill
which modifies the array in place:
According to discussions here using fill is faster for small datasets, but as n increases the performance gain is lost, so it mainly depends on remembering the syntax.