Creating a structured array from a list

I have a simple list of elements, and I'm trying to make a structured array from it.

This naive approach fails:

y = np.array([1,2,3], dtype=[('y', float)])
TypeError: expected an object with a buffer interface

Placing 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 first create an array from a list:

y = np.array(np.array([1,2,3]), dtype=[('y', float)])

I am a little puzzled. How did it happen that the latter works, but numpycannot sort information when providing a simple list?

What is the recommended way? Creating an intermediate arraymay not greatly affect performance, but is it suboptimal?

I am also surprised that they will not 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 how numpypicky I was about input types. Something must be missing me.

+6
1

, np.array , . dtype , . .

np.array([[1,2,3],[4,5,6]])

tuple . .

, list of tuples .

In [382]: dt=np.dtype([('y',int)])
In [383]: np.array(alist,dt)

TypeError: a bytes-like object is required, not 'int'

"1.12.0". , .

, .

In [384]: np.array([tuple(i) for i in alist],dt)
Out[384]: 
array([(1,), (2,), (3,)], 
      dtype=[('y', '<i4')])

SO, , . , ( , , ).

, astype:

In [385]: np.array(np.array(alist),dt)
Out[385]: 
array([[(1,)],
       [(2,)],
       [(3,)]], 
      dtype=[('y', '<i4')])
In [386]: np.array(alist).astype(dt)
Out[386]: 
array([[(1,)],
       [(2,)],
       [(3,)]], 
      dtype=[('y', '<i4')])

. (3,). astype a (3,1) (3,1) .

, tuples np.array, - .

[(3,), (1,), (2,)]
[record, record, record]

[[1],[2],[3]]

[[record],[record],[record]]

dtype (),

In [388]: np.array([tuple(i) for i in alist],int)
Out[388]: 
array([[1],
       [2],
       [3]])

dtype , .


dtype

In [389]: dt1=np.dtype([('y',int,(2,))])
In [390]: np.ones((3,), dt1)
Out[390]: 
array([([1, 1],), ([1, 1],), ([1, 1],)], 
      dtype=[('y', '<i4', (2,))])
In [391]: np.array([([1,2],),([3,4],)])
Out[391]: 
array([[[1, 2]],

       [[3, 4]]])
In [392]: np.array([([1,2],),([3,4],)], dtype=dt1)
Out[392]: 
array([([1, 2],), ([3, 4],)], 
      dtype=[('y', '<i4', (2,))])

( ) .

In [393]: dt1=np.dtype([('x',dt,(2,))])
In [394]: dt1
Out[394]: dtype([('x', [('y', '<i4')], (2,))])
In [395]: np.ones((2,),dt1)
Out[395]: 
array([([(1,), (1,)],), ([(1,), (1,)],)], 
      dtype=[('x', [('y', '<i4')], (2,))])

numpy

+3

Source: https://habr.com/ru/post/1016720/


All Articles