I want to make an array that is filled with a particular value. For simple data types, I can do this with np.full
. For example, the following code will generate an array of length 10, where each value is the 64-bit integer 10:
import numpy as np
arr = np.full((10,), -1, np.int64)
But I have more complicated, mixed, array data types. For example, I'd expect the following code to work:
import numpy as np
data_type = [("value_1", np.int64), ("value_2", np.float64)]
default = (-1, np.nan)
arr = np.full((10,), default, data_type)
This gives ValueError: could not broadcast input array from shape (2) into shape (10)
. I know why (it tries putting each value of my default into a separate element of my array) - it just isn't what I want it to do (putting my entire default into each element of the array.
I'd be able to get around this by making my default something that numpy recognizes to be a single element. For example, this works:
default_array = np.array([default], data_type)
new_default = default_array[0]
arr = np.full((10,), new_default, data_type)
But this is sure to confuse any future readers of my code, myself included.
Now on to my actual question:
Is there any way to make this new_default
object without going through the hoop of first creating an array?
The new_default
object is of type numpy.void
, but I can't seem to create my own such object through, e.g. np.void(default)
.