Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a structured array from a list

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.

like image 409
Jérôme Avatar asked Apr 24 '17 09:04

Jérôme


People also ask

Can a list be converted to array in Python?

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.

How does the structured array can be created using NumPy object explain with example?

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.

What is f4 in NumPy?

'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.


1 Answers

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]])
like image 192
Mustapha Babatunde Avatar answered Sep 28 '22 18:09

Mustapha Babatunde