Reputation: 117
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.
Upvotes: 3
Views: 2281
Reputation: 339300
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]
Upvotes: 1
Reputation: 117
This solution fits the best for me:
dt64[(dt64.astype('M8[M]') - dt64.astype('M8[Y]')).view(int) == 2]
Thanks to Paul Panzer.
Upvotes: 0
Reputation: 1373
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]
Upvotes: 0
Reputation: 7510
If i understand you correctly this would do it:
[np.datetime64(i,'M') for i in dt64]
Upvotes: 3