How can I make such a numpy datastructure that can store datetime and float at the same time?
array([[ 2017-01-30 00:00:00, 1.0],
[ 2017-01-31 00:00:00, 2.0]])
How can I make such a numpy datastructure that can store datetime and float at the same time?
array([[ 2017-01-30 00:00:00, 1.0],
[ 2017-01-31 00:00:00, 2.0]])
You can use a structured array with heterogenous tuples:
import numpy as np
x = np.array([(np.datetime64('2017-01-30'), 1.0),
(np.datetime64('2017-01-31'), 2.0)],
dtype=[('datetime', 'datetime64[D]'), ('number', 'f8')])
The syntax is a bit similar to dicts then:
>>> x['datetime']
array(['2017-01-30', '2017-01-31'], dtype='datetime64[D]')
>>> x['number']
array([ 1., 2.])
>>> x['datetime'][0] + 5
numpy.datetime64('2017-02-04')
>>> x['number'][1] + 5
7.0
Note that Pandas might be more suited to your needs.
Use a structured array:
import numpy as np
desc = np.dtype([('date', '<M8[s]'), ('float', np.float64)])
a = np.array([(np.datetime64('2017-01-30 00:00:00'), 1.0),
(np.datetime64('2017-01-31 00:00:00'), 2.0)], dtype=desc)
print(a)
print(repr(a))
Output:
[('2017-01-30T00:00:00', 1.) ('2017-01-31T00:00:00', 2.)]
array([('2017-01-30T00:00:00', 1.), ('2017-01-31T00:00:00', 2.)],
dtype=[('date', '<M8[s]'), ('float', '<f8')])
This is not possible as ndarray has to be homogenous i.e. of same data type. To solve your purpose, you could use a list or tuple instead of an array.