I have a simple list of elements and I'm trying to make a structured array out of it.
This naive approach fails:
y = np.array([1,2,3], dtype=[('y', float)])
TypeError: expected an object with a buffer interface
Putting each element in a tuple works:
# Manuel way
y = np.array([(1,), (2,), (3,)], dtype=[('y', float)])
# Comprehension
y = np.array([tuple((x,)) for x in [1,2,3]], dtype=[('y', float)])
It also works if I create an array from the list first:
y = np.array(np.array([1,2,3]), dtype=[('y', float)])
I'm a bit puzzled. How come the latter works but numpy
couldn't sort things out when provided a simple list?
What is the recommended way? Creating that intermediate array
might not have a great performance impact, but isn't this suboptimal?
I'm also surprised that those won't work:
# All lists
y = np.array([[1,], [2,], [3,]], dtype=[('y', float)])
TypeError: expected an object with a buffer interface
# All tuples
y = np.array(((1,), (2,), (3,)), dtype=[('y', float)])
ValueError: size of tuple must match number of fields.
I'm new to structured arrays and I don't remember numpy
being that picky about input types. There must be something I'm missing.
Lists can be converted to arrays using the built-in functions in the Python numpy library. numpy provides us with two functions to use when converting a list into an array: numpy.
Creating a Structured Numpy Array For that we need to pass the type of above structure type i.e. schema in dtype parameter. Let's create a dtype for above structure i.e. Let's create a numpy array based on this dtype i.e. It is basically the structure type specifying a structure of String of size 10, float and int.
'f' is the shorthand for 'float32'. 'f4' also means 'float32' because it has 4 bytes and each byte has 8 bits. Similarly, 'f8' means 'float64' because 8*8 = 64.
np.array() function accepts list of list as input. So if you want to create a 2 * 2 matrix, for example, this is what you need to do
X = np.array([[1,2], [3,4]])
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