Reputation: 5496
I have the following list:
[(10, 1.1, 1.2, 12),
(11, 2.1, 2.2, 22),
(12, 3.1, 3.2, 32),
(13, 4.1, 4.2, 42)]
And the following numpy datatype:
dt=np.dtype([('a', np.uint32), ('b', np.float64), ('c', np.float64), ('d', np.uint32)])
How could I convert above list into a numpy array of 4 rows 1 column having each row the elements stored as a numpy structured datatype?
Upvotes: 2
Views: 290
Reputation: 31319
User @hpaulj already answered in the comments, but with a bit more detail:
import numpy as np
data = [
(10, 1.1, 1.2, 12),
(11, 2.1, 2.2, 22),
(12, 3.1, 3.2, 32),
(13, 4.1, 4.2, 42)
]
dt = np.dtype([('a', np.uint32), ('b', np.float64), ('c', np.float64), ('d', np.uint32)])
arr = np.array(data, dt)
print(arr)
print(arr.dtype)
print(arr['a'], arr['b'])
print(arr[0], arr[1])
Output:
[(10, 1.1, 1.2, 12) (11, 2.1, 2.2, 22) (12, 3.1, 3.2, 32)
(13, 4.1, 4.2, 42)]
[('a', '<u4'), ('b', '<f8'), ('c', '<f8'), ('d', '<u4')]
[10 11 12 13] [1.1 2.1 3.1 4.1]
(10, 1.1, 1.2, 12) (11, 2.1, 2.2, 22)
Note that the shape of the arr
array is (4,)
, but considering that's just an array of 4 elements, each element a named structured datatype as required, I would assume it meets the need in the cleanest way.
If somehow the solution doesn't meet your needs, please post a comment indicating what you need to be different and why.
Upvotes: 1