3

I have an array like this one:

dt64 = array(['1970-01-01', '1970-01-02', '1970-02-03', '1970-02-04',
      '1970-03-05', '1970-03-06', '1970-04-07', '1970-04-08',
      '1970-05-09', '1970-05-10', '1970-06-11', '1970-06-12',
      '1970-07-13', '1970-07-14'], dtype='datetime64[D]')

Now I want to plot some data associated with the single element of the array. In the figure I want to plot using matplotlib I need to draw a line that changes color for some months.

I want to draw the months mar to aug in orange and the others in blue.

I think I have to do two plt.plot lines, one for the orange line and one for the blue line.

My problem now is, I struggle to slice these datetime64 object in a way that returns the month to to compare them with the required months.

So far I have:

import numpy as np
from matplotlib import pyplot as plt

def md_plot(dt64=np.array, md=np.array):
    """Erzeugt Plot der Marsdistanz (y-Achse) zur Zeit (x-Achse)."""
    plt.style.use('seaborn-whitegrid')

    y, m, d = dt64.astype(int) // np.c_[[10000, 100, 1]] % np.c_[[10000, 100, 100]]
    dt64 = y.astype('U4').astype('M8') + (m-1).astype('m8[M]') + (d-1).astype('m8[D]')

    plt.plot(dt64, md, color='orange', label='Halbjahr der steigenden Temperaturen')
    plt.plot(dt64, md, color='blue', label='Halbjahr der fallenden Temperaturen')

    plt.xlabel("Zeit in Jahren\n")
    plt.xticks(rotation = 45)
    plt.ylabel("Marsdistanz in AE\n(1 AE = 149.597.870,7 km)")

plt.figure('global betrachtet...') # diesen Block ggf. auskommentieren
#plt.style.use('seaborn-whitegrid')
md_plot(master_array[:,0], master_array[:,1]) # Graph

plt.show()
plt.close()

This idea seemed to work, but won't work for a whole array:

In [172]: dt64[0].astype(datetime.datetime).month
Out[172]: 1

I really try to avoid Pandas because I don't want to bloat my script when there is a way to get the task done by using the modules I am already using. I also read it would decrease the speed here.

zorrolo
  • 117
  • 9

4 Answers4

3

If i understand you correctly this would do it:

[np.datetime64(i,'M') for i in dt64]
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
  • @Chistian This only generates a list of datetime64 objects like ```python [numpy.datetime64('1895-09'), numpy.datetime64('1895-09'), numpy.datetime64('1895-09'), numpy.datetime64('1895-09'), ...] ``` How can I erase the year also to use the result for comparing to find the slices of ```dt64``` that I am looking for? – zorrolo Mar 31 '19 at 21:37
1

Converting to python datetime in an intermediate step:

from datetime import datetime
import numpy as np

datestrings = np.array(["18930201", "19840404"])
months = np.array([datetime.strptime(d, "%Y%m%d").month for d in datestrings])

print(months)

# out: [2 4]
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
0

My version of numpy May be dated, but when I ran np.datetime64(dt64[0]) I got numpy.datetime64('1970-01')

To get just the month (if that’s what you are looking for) try:

np.datetime_as_string(dt64[0]).split('-')[1]
Ethan
  • 1,363
  • 1
  • 6
  • 8
  • Although I got this: ``` In [211]: int(np.datetime_as_string(dt64[0]).split('-')[1]) == 1 Out[211]: True ``` I cannot get the intervals from the ```dt64``` array: ```python In [221]: dt64[np.argwhere(int(np.datetime_as_string(dt64[i]).split('-')[1]) == 1)[0,0],0] Traceback (most recent call last): File "", line 1, in dt64[np.argwhere(int(np.datetime_as_string(dt64[i]).split('-')[1]) == 1)[0,0],0] IndexError: index 0 is out of bounds for axis 0 with size 0 ``` – zorrolo Mar 31 '19 at 21:39
0

This solution fits the best for me:

dt64[(dt64.astype('M8[M]') - dt64.astype('M8[Y]')).view(int) == 2]

Thanks to Paul Panzer.

zorrolo
  • 117
  • 9