How to solve TypeError: The DTypes <class 'numpy.dtype[uint8]'> and <class 'numpy.dtype[datetime64]'> do not have a common DType?

How to solve TypeError: The DTypes <class 'numpy.dtype[uint8]'> and <class 'numpy.dtype[datetime64]'> do not have a common DType?

我有一个数据框,我想使用所有列的堆叠图来绘制它

    date              company1           company2           company3
0   2015-09-30  0.1729652326951854  5.10825384154414    5.28662587089132
1   2015-12-31  0.33177760613144625 5.341402694012068   7.757158664745589
2   2016-03-31  0.45978954321258786 0.601947573082123   14.280848001613228
3   2016-06-30  0.08512062667254938 0.26628902842588686 9.342680735839917
4   2016-09-30  0.07052086314882283 10.032170981625246  8.964205526466738
5   2016-12-31  0.06143896111634454 10.06041088786925   8.3778390910586
6   2017-03-31  0.03742645731812014 7.156923204928792   6.793302965780993
7   2017-06-30  0.1032395546373315  5.438273795868809   4.857798532828831

我做了以下事情

df['date'] = pd.to_datetime(df.date)
fig, ax = plt.subplots(figsize=(9,6), dpi= 80)
ax = exchanges_disagg_data.plot.area(legend=None, figsize=(9,6), alpha=0.9)

我收到以下错误消息。

TypeError: The DTypes <class 'numpy.dtype[uint8]'> and <class 'numpy.dtype[datetime64]'> do not have a common DType. For example they cannot be stored in a single array unless the dtype is `object`.

然后我试了

df.date= df['date'].dt.strftime('%Y-%m-%d')

我得到了情节,但我得到的不是日期时间 x 刻度,而是索引号...

这很令人沮丧,有人知道如何解决这个问题吗?非常感谢。

注:np.nan为float类型,pd.NaT为datetime null类型。您的代码的问题是空值已填充 np.nan

我在执行以下操作时遇到了同样的错误....

df['date'] = np.where((df['date2'].notnull()) & (df['date3'].notnull()),df['date2']-df['date3'],np.nan)

这里的问题是date2和date3的日期差异是datetime类型,而“np.nan”的类型是float/int。要将其保存到 df['date'],数据类型应相同。在日期时间类型中,空日期是“pd.NaT”。所以当我用下面的代码替换上面的代码时。它对我有用。你也可以试试..

df['date'] = np.where((df['date2'].notnull()) & (df['date3'].notnull()),df['date2']-df['date3'],pd.NaT)

因此您可以将数据中存在的空值替换为 pd.NaT 而不是 np.nan

你也可以使用下面的东西...

df['date'].replace(np.NaN, pd.NaT)

df['date'].fillna(pd.NaT)

希望对您有所帮助:)