Eldir
Eldir

Reputation: 84

numpy dtype duplicate the array

I try to add a dtype in a numpy array (for the creation after of a ply file), but when I write this:

list_example = np.array([[1,2,3]], dtype=[('example', 'i4', (3,))]

The result is :

array([[([1, 1, 1],), ([2, 2, 2],), ([3, 3, 3],)]],
      dtype=[('example', '<i4', (3,))])

And i don't understand why it's duplicate every components of my array. Because if I do this:

np.array([([1,2,3], 255)], dtype = [('example', 'i4', (3,)), ('color', 'u1')])

I obtain:

array([([1, 2, 3], 255)], dtype=[('example', '<i4', (3,)), ('color', 'u1')])

where my array dont duplicate [1,2,3]

Thanks for your help!

Upvotes: 1

Views: 119

Answers (2)

hpaulj
hpaulj

Reputation: 231385

When creating structured arrays, the distinction between list and tuple is important. The inputs should match the print display, as your working case shows.

For the first dtype, try:

In [525]: np.zeros(1, dtype=[('example', 'i4', (3,))])
Out[525]: array([([0, 0, 0],)], dtype=[('example', '<i4', (3,))])

imitating that:

In [526]: np.array([([1,2,3],)], dtype=[('example', 'i4', (3,))])
Out[526]: array([([1, 2, 3],)], dtype=[('example', '<i4', (3,))])

np.array([([1,2,3])], dtype=[('example', 'i4', (3,))]) doesn't help because the () include a single list, without a comma, so they do nothing. Your dtype has one field, so the input must have a single element tuple per record.

Upvotes: 2

Mohammad
Mohammad

Reputation: 3396

You can use rec.fromarrays

>>> np.rec.fromarrays([([1,2,3])], dtype=[('example', 'i4', (3,))])

rec.array(([1, 2, 3],),
          dtype=[('example', '<i4', (3,))])

Upvotes: 1

Related Questions