Numpy Structured Array aus mehreren Arrays erzeugen

mit matplotlib, NumPy, pandas, SciPy, SymPy und weiteren mathematischen Programmbibliotheken.
Antworten
rogerb
User
Beiträge: 878
Registriert: Dienstag 26. November 2019, 23:24

Hallo zusammen,

weiß jemand wie man mehrere numpy arrays zu einem structured array mit verschiedenen Datentypen zusammensetzt?

Code: Alles auswählen

import numpy as np

column1 = np.array([1, 2, 3])
column2 = np.array(["A", "B", "C"])

data_types = dtype=([("column1", int), ("column2", str)])

target = np.stack((column1, column2), axis=1)
Mit np.stack() kann ich die arrays zwar zusammenfügen, da np.stack() aber keinen dtype akzeptiert, enthält das neue array nur strings.

Code: Alles auswählen

[['1' 'A']
 ['2' 'B']
 ['3' 'C']]
 
Gewünscht währe etwas in der Art:

Code: Alles auswählen

[(1 'A')
 (2 'B')
 (3 'C')]
Benutzeravatar
__blackjack__
User
Beiträge: 14336
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

Man könnte vorher eine entsprechende Liste mit Tupeln erstellen:

Code: Alles auswählen

In [15]: data_types = dtype=([("column1", int), ("column2", "S1")])             

In [16]: target = np.array(list(zip(column1, column2)), dtype=data_types)       

In [17]: target                                                                 
Out[17]: 
array([(1, b'A'), (2, b'B'), (3, b'C')],
      dtype=[('column1', '<i8'), ('column2', 'S1')])
Oder ein leeres Array erstellen und dann die Spaltenwerte zuweisen:

Code: Alles auswählen

In [18]: target = np.zeros(len(column1), dtype=data_types)                      

In [19]: target                                                                 
Out[19]: 
array([(0, b''), (0, b''), (0, b'')],
      dtype=[('column1', '<i8'), ('column2', 'S1')])

In [20]: target["column1"] = column1                                            

In [21]: target                                                                 
Out[21]: 
array([(1, b''), (2, b''), (3, b'')],
      dtype=[('column1', '<i8'), ('column2', 'S1')])

In [22]: target["column2"] = column2                                            

In [23]: target                                                                 
Out[23]: 
array([(1, b'A'), (2, b'B'), (3, b'C')],
      dtype=[('column1', '<i8'), ('column2', 'S1')])
„Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.“ — Brian W. Kernighan
rogerb
User
Beiträge: 878
Registriert: Dienstag 26. November 2019, 23:24

Super! Vielen Dank!
Antworten