gpt4 book ai didi

python - 如何将 `numpy.datetime64` 列表转换为 `matplotlib.dates` ?

转载 作者:行者123 更新时间:2023-12-01 02:34:42 26 4
gpt4 key购买 nike

这是我的简单对象:

[numpy.datetime64('2017-01-03T00:00:00.000000000'),
numpy.datetime64('2017-01-04T00:00:00.000000000'),
numpy.datetime64('2017-01-05T00:00:00.000000000'),
numpy.datetime64('2017-01-06T00:00:00.000000000'),
numpy.datetime64('2017-01-09T00:00:00.000000000'),
numpy.datetime64('2017-01-10T00:00:00.000000000'),
numpy.datetime64('2017-01-11T00:00:00.000000000'),
numpy.datetime64('2017-01-12T00:00:00.000000000'),
numpy.datetime64('2017-01-13T00:00:00.000000000'),
numpy.datetime64('2017-01-16T00:00:00.000000000'),
numpy.datetime64('2017-01-17T00:00:00.000000000'),
numpy.datetime64('2017-01-18T00:00:00.000000000'),
numpy.datetime64('2017-01-19T00:00:00.000000000'),
numpy.datetime64('2017-01-20T00:00:00.000000000'),
numpy.datetime64('2017-01-23T00:00:00.000000000'),
numpy.datetime64('2017-01-24T00:00:00.000000000'),
numpy.datetime64('2017-01-25T00:00:00.000000000'),
numpy.datetime64('2017-01-26T00:00:00.000000000'),
numpy.datetime64('2017-01-27T00:00:00.000000000'),
numpy.datetime64('2017-02-01T00:00:00.000000000')]

不使用循环将空列表一一转换,是否有任何快捷方式?谢谢。

最佳答案

我最喜欢的解决方案似乎有点隐藏在这个线程中: Converting between datetime, Timestamp and datetime64 ,即使用tolist()。由于 tolist() 返回不同的类型,具体取决于数组类型,因此需要转换为 ms 才能获取 datetime 对象。 datetime 对象可以直接使用 matplotlib 进行绘制,也可以对其应用 matplotlib.dates.date2num()

因此,如果 a 是上面的 numpy 数组,

x = a.astype("M8[ms]").tolist()

结果为日期时间对象列表。

完整示例:

import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import matplotlib.dates as mdates

a = np.array([np.datetime64('2017-01-03T00:00:00.000000000'),
np.datetime64('2017-01-04T00:00:00.000000000'),
np.datetime64('2017-01-05T00:00:00.000000000'),
np.datetime64('2017-01-06T00:00:00.000000000'),
np.datetime64('2017-01-09T00:00:00.000000000'),
np.datetime64('2017-01-10T00:00:00.000000000'),
np.datetime64('2017-01-11T00:00:00.000000000'),
np.datetime64('2017-01-12T00:00:00.000000000'),
np.datetime64('2017-01-13T00:00:00.000000000'),
np.datetime64('2017-01-16T00:00:00.000000000'),
np.datetime64('2017-01-17T00:00:00.000000000'),
np.datetime64('2017-01-18T00:00:00.000000000'),
np.datetime64('2017-01-19T00:00:00.000000000'),
np.datetime64('2017-01-20T00:00:00.000000000'),
np.datetime64('2017-01-23T00:00:00.000000000'),
np.datetime64('2017-01-24T00:00:00.000000000'),
np.datetime64('2017-01-25T00:00:00.000000000'),
np.datetime64('2017-01-26T00:00:00.000000000'),
np.datetime64('2017-01-27T00:00:00.000000000'),
np.datetime64('2017-02-01T00:00:00.000000000')])

x = a.astype("M8[ms]").tolist()
y = np.random.rand(len(a))

plt.plot(x, y, color="limegreen")

plt.show()

关于python - 如何将 `numpy.datetime64` 列表转换为 `matplotlib.dates` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46376252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com