Skip to content Skip to sidebar Skip to footer

Converting String To Date In Numpy Unpack

I'm learning how to extract data from links and then proceeding to graph them. For this tutorial, I was using the yahoo dataset of a stock. The code is as follows import matplotli

Solution 1:

With a guess as to the csv format, I can use the numpy 'native' datetime dtype:

In [183]: txt = ['2020-10-23 1 2.3']*3                                                                               
In [184]: txt                                                                                                        
Out[184]: ['2020-10-23 1 2.3', '2020-10-23 1 2.3', '2020-10-23 1 2.3']

If I let genfromtxt do its own dtype conversions:

In [187]: np.genfromtxt(txt, dtype=None, encoding=None)                                                              
Out[187]: 
array([('2020-10-23', 1, 2.3), ('2020-10-23', 1, 2.3),
       ('2020-10-23', 1, 2.3)],
      dtype=[('f0', '<U10'), ('f1', '<i8'), ('f2', '<f8')])

the date column is rendered as a string.

If I specify a datetime64 format:

In [188]: np.array('2020-10-23', dtype='datetime64[D]')                                                              
Out[188]: array('2020-10-23', dtype='datetime64[D]')

In [189]: np.genfromtxt(txt, dtype=['datetime64[D]',int,float], encoding=None)                                       
Out[189]: 
array([('2020-10-23', 1, 2.3), ('2020-10-23', 1, 2.3),
       ('2020-10-23', 1, 2.3)],
      dtype=[('f0', '<M8[D]'), ('f1', '<i8'), ('f2', '<f8')])

This date appears to work in plt

In [190]: plt.plot_date(_['f0'], _['f1'])       

I used genfromtxt because I'm more familiar with its ability to handle dtypes.

Post a Comment for "Converting String To Date In Numpy Unpack"