Erstellen eines Arrays mit einem einzelnen strukturierten Element, das ein Array enthält

Oct 06 2020

Ich habe einen dtype wie diesen:

>>> dt = np.dtype([('x', object, 3)])
>>> dt
dtype([('x', 'O', (3,))])

Ein Feld mit dem Namen 'x' enthält drei Zeiger. Ich möchte ein Array mit einem einzelnen Element dieses Typs erstellen:

>>> a = np.array([(['a', 'b', 'c'])], dtype=dt)
>>> b = np.array([(np.array(['a', 'b', 'c'], dtype=object))], dtype=dt)
>>> c = np.array((['a', 'b', 'c']), dtype=dt)
>>> d = np.array(['a', 'b', 'c'], dtype=dt)

>>> e = np.array([([['a', 'b', 'c']])], dtype=dt)

Alle fünf Aussagen liefern das gleiche falsche Ergebnis:

array([[(['a', 'a', 'a'],), (['b', 'b', 'b'],), (['c', 'c', 'c'],)]],
      dtype=[('x', 'O', (3,))])

Wenn ich versuche, die innere Liste / das innere Array zu löschen, wird eine Fehlermeldung angezeigt:

>>> f = np.array([('a', 'b', 'c')], dtype=dt)
ValueError: could not assign tuple of length 3 to structure with 1 fields.

Der gleiche Fehler tritt auf für

>>> g = np.array(('a', 'b', 'c'), dtype=dt)

Ich habe keine möglichen Kombinationen mehr, um es zu versuchen. Das Ergebnis, das ich suche, ist

 array([(['a', 'b', 'c'],)], dtype=[('x', 'O', (3,))])

Wie erstelle ich ein Array mit einem Element des angegebenen dtype?

Bisher habe ich nur die manuelle Zuordnung gefunden:

z = np.empty(1, dtype=dt)
z['x'][0, :] = ['a', 'b', 'c']

ODER

z[0]['x'] = ['a', 'b', 'c']

Dies scheint eine unnötige Problemumgehung für etwas zu np.arraysein, das sofort einsatzbereit sein sollte.

Antworten

1 hpaulj Oct 05 2020 at 22:50
In [44]: dt = np.dtype([('x', object, 3)])   # corrected
In [45]: dt
Out[45]: dtype([('x', 'O', (3,))])
In [46]: np.empty(3, dt)
Out[46]: 
array([([None, None, None],), ([None, None, None],),
       ([None, None, None],)], dtype=[('x', 'O', (3,))])
In [47]: np.array([(['a','b','c'],)], dt)
Out[47]: array([(['a', 'b', 'c'],)], dtype=[('x', 'O', (3,))])

Die Eingabeformatierung sollte mit der Ausgabeformatierung übereinstimmen.

In [48]: arr = np.empty(3, dt)
In [49]: arr['x']
Out[49]: 
array([[None, None, None],
       [None, None, None],
       [None, None, None]], dtype=object)
In [50]: arr['x'][0]
Out[50]: array([None, None, None], dtype=object)
In [51]: arr['x'][0] = ['a','b','c']
In [52]: arr
Out[52]: 
array([(['a', 'b', 'c'],), ([None, None, None],), ([None, None, None],)],
      dtype=[('x', 'O', (3,))])