The following code constructs a NumPy array with a dtype object:
dt = np.dtype([
("index", np.int32),
("timestamp", np.int32),
("volume", np.float32)
])
arr = np.array([
[0, 20, 3],
[1, 21, 2],
[2, 23, 8],
[3, 26, 5],
[4, 31, 9]
]).astype(dt)
The expected result of arr
would be:
>>> arr
array([[ 0, 20, 334.],
[ 1, 21, 254.],
[ 2, 23, 823.],
[ 3, 26, 521.],
[ 4, 31, 943.]])
>>> arr[0]
array([ 0, 20, 334.])
But what the code above is creating is actually this:
>>> arr
array([[( 0, 0, 0.), ( 20, 20, 20.), (334, 334, 334.)],
[( 1, 1, 1.), ( 21, 21, 21.), (254, 254, 254.)],
[( 2, 2, 2.), ( 23, 23, 23.), (823, 823, 823.)],
[( 3, 3, 3.), ( 26, 26, 26.), (521, 521, 521.)],
[( 4, 4, 4.), ( 31, 31, 31.), (943, 943, 943.)]],
dtype=[('index', '<i4'), ('timestamp', '<i4'), ('volume', '<f4')])
>>> arr[0]
array([( 0, 0, 0.), ( 20, 20, 20.), (334, 334, 334.)],
dtype=[('index', '<i4'), ('timestamp', '<i4'), ('volume', '<f4')])
Why is NumPy creating a version of every value for every data type instead of mapping each column to its own data type (and only this one)? I'm guessing that I did something wrong there. Is there a way to get to the result I was expecting?