timedelta64[ns] -> FutureWarning:不推荐传递 timedelta64-dtype 数据,将在未来版本中引发 TypeError

gie*_*s0r 5 python plot matplotlib python-3.x pandas

假设df['time']是从类型timedelta64[ns]df['a']以及df['b']从类型float64,这两个系列可以被绘制这样的:

import pandas as pd
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, sharex=True)

time_values = pd.to_datetime(df['time'])
axs[0].plot(time_values, df['a'])
axs[1].plot(time_values, df['b'])
plt.show()
Run Code Online (Sandbox Code Playgroud)

这有效..但给出了以下警告:

FutureWarning: Passing timedelta64-dtype data is deprecated, will raise a TypeError in a future version
Run Code Online (Sandbox Code Playgroud)

那么应该使用什么来代替在pd.to_datetime中显示timedelta64[ns]为人类可读的时间matplotlib

小智 2

我在使用 pandas 从 SQL 读取时间数据时遇到了同样的问题。这两行解决了我的问题。我尝试寻找另一种直接的解决方案,但没有成功。

time_values = df['time'].apply(lambda x: np.nan if pd.isnull(x) else str(x)[-8:])
time_values = pd.to_datetime(time_values, format='%H:%M:%S').dt.time
Run Code Online (Sandbox Code Playgroud)