1

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]])
lioli
  • 191
  • 1
  • 13
  • 1
    Look up [structured arrays](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.rec.html). – sascha Nov 09 '17 at 19:03
  • Have you tried to convert date to float and save it as number? – ingvar Nov 09 '17 at 19:06
  • 1
    `np.datetime64` is a dtype that stores dates. But to put those in in the same array as floats you have to use a compound dtype, the aforementioned `structured array`. – hpaulj Nov 09 '17 at 19:08

3 Answers3

2

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.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
2

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')])
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • 1
    Nitpick: Your example gives a [structured array](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.rec.html#module-numpy.doc.structured_arrays), not a [record array](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.rec.html#record-arrays). The former has a Python type of `np.ndarray`; the latter has a Python type of `np.recarray`. – Mark Dickinson Nov 09 '17 at 21:46
  • @MarkDickinson Thanks for the hint. Corrected. – Mike Müller Nov 12 '17 at 10:09
0

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.

Prateek
  • 73
  • 8