【问题标题】:TypeError: ufunc subtract cannot use operands with types dtype('<M8[ns]') and dtype('float64')类型错误:ufunc 减法不能使用类型为 dtype('<M8[ns]') 和 dtype('float64') 的操作数
【发布时间】:2017-11-19 16:19:33
【问题描述】:

我按照 sentdex 的视频教程遇到了错误代码。但是,当我想在 ax2 上为我的 Volume 绘制条形图时,它会给出主题中列出的错误代码。请帮忙。我是 Python 0 编程经验的新手。

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
style.use('ggplot')

df = pd.read_csv('C:\\Users\\ngjun95\\Downloads\\7120.KL.csv',     parse_dates=True, index_col=0)
df['100ma'] = df['Adj Close'].rolling(window=100, min_periods=0).mean()

print(df.head())

ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)

ax1.plot(df.index, df['Adj Close'])
ax1.plot(df.index, df['100ma'])
ax2.bar(df.index, df['Volume'])

plt.show()

【问题讨论】:

    标签: python finance


    【解决方案1】:

    似乎是 Matplotlib 和 Numpy 之间的日期转换问题。 https://github.com/matplotlib/matplotlib/issues/9610

    我遇到同样问题的时间最长。

    df.index.to_pydatetime() 对我有用。

    【讨论】:

    • 这里有更多关于我关于这个问题的故事的信息:在旧版本的 Pandas 中(可能在 0.17 或 0.18 左右;不确定),我没有这样的问题。然后,一旦我开始使用 .2,在绘制正确索引的时间序列时,我在 x 轴上遇到了自动日期的问题。从那时起,.to_pydatetime() 解决方案对我有用。但它有一些缺点,例如图表上的空白区域,某些日期没有可用的数据。幸运的是,几天前,我更新到 Pandas 0.21.1,不再需要这个工作。所以,我建议你更新一下,看看会发生什么。
    【解决方案2】:

    老话题,但是 df.index.to_pydatetime() 并没有解决我的 seaborn.regplot() 问题。对我来说,date2num 效果很好。

    import matplotlib.dates as mdates
    
    sns.regplot(x=mdates.date2num(df.index), y=df['target'])
    

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2019-10-23
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多