如何使用datetimes和nan对象打印数据?

2024-04-25 10:09:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想绘制一个函数与时间的关系图,但需要包括一些间隙。我的数据如下所示:

function = [0, 5, 19, 10, nan, nan, 10, 15]
times = [10, 11, 12, 13, nan, nan, 16, 17]

我需要这个图来显示13-16之间的差距。现在,当我试图绘制它给我一个错误

TypeError: unsupported operand type(s) for -: 'float' and 'datetime.datetime'

我相信这是由日期列表中的“南”造成的。我怎样才能解决这个问题


2条回答

您可以在不使用numpy的情况下使用熊猫,如下所示:

from matplotlib import pyplot as plt
import pandas as pd

df = pd.DataFrame({"times":[10, 11, 12, 13, None, None, 16, 17], "function" :[0, 5, 19, 10, None, None, 10, 15]})
print(df)

plt.plot(df.times, df.function)
plt.xlabel('times')
plt.ylabel('function')
plt.show()

#Here is the df with NaN values:
   times  function
0   10.0       0.0
1   11.0       5.0
2   12.0      19.0
3   13.0      10.0
4    NaN       NaN
5    NaN       NaN
6   16.0      10.0
7   17.0      15.0

enter image description here

使用numpy,您可以用matplotlib正确处理的np.nan替换nan

import matplotlib.pyplot as plt
import numpy as np

function = [0, 5, 19, 10, np.nan,np.nan, 10, 15]
times = [10, 11, 12, 13, np.nan,np.nan,16, 17]
plt.plot(times, function)
plt.show()

enter image description here

相关问题 更多 >