python - 如何从 np.datetime64 对象中获取月份,而不是使用 pandas

标签 python python-3.x numpy date datetime

我有一个这样的数组:

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]')

现在我想绘制一些与数组的单个元素相关的数据。在我想使用 matplotlib 绘图的图中,我需要绘制一条会在几个月内改变颜色的线。

我想用橙色画出 3 月到 8 月,用蓝色画其他月份。

我想我必须做两条 plt.plot 线,一条用于橙色线,一根用于蓝色线。

我现在的问题是,我很难以返回月份的方式对这些 datetime64 对象进行切片,以便将它们与所需的月份进行比较。

到目前为止我有:

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()

这个想法似乎可行,但不适用于整个数组:

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

我真的尽量避免使用 Pandas,因为当有办法通过使用我已经在使用的模块来完成任务时,我不想让我的脚本膨胀。我还读到它会降低速度 here .

最佳答案

如果我理解正确的话,可以这样做:

[np.datetime64(i,'M') for i in dt64]

关于python - 如何从 np.datetime64 对象中获取月份,而不是使用 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55444766/

相关文章:

python - pygame 中的图像未更新

python - matplotlib savefig 线程安全吗?

unicode - 在 Python 3 中运行时更改 stdin/stdout 的编码

python - 如何将 Celery 与 asyncio 结合使用?

python - 操作系统错误 : exception: access violation reading with Cyphon basic example

python - 如何从 opencv 获得准确的 idft 结果?

python - 快速确定 Python 中小于 10 亿的数字是否为质数

python - 在 Python 中使用字典代替 Case/Switch 语句

python - 计算 numpy 数组中成对列的组合

python - 彩色 3D 图