【问题标题】:Pandas Data Frame from Web is not Displaying Correctly Compared to the Native CSV File与本机 CSV 文件相比,来自 Web 的 Pandas 数据框显示不正确
【发布时间】:2019-08-31 09:00:08
【问题描述】:

我正在尝试制作一个分析股票的程序,现在我编写了一个简单的 Python 脚本来绘制移动平均线。从本机路径中提取 CSV 文件可以正常工作,但是当我从 Web 获取它时,它不起作用。一直显示错误:“列表”对象没有属性“日期”

它在 .CSV 上运行良好,但网络上的东西搞砸了。 如果我运行 print(df),它会非常奇怪地显示表格。

import pandas as pd 
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_html("https://finance.yahoo.com/quote/AAPL/history?period1=1428469200&period2=1554699600&interval=1d&filter=history&frequency=1d")
x = df.Date
y = df.Close

a = df['Close'].rolling(50, min_periods=50).mean()
b = df['Close'].rolling(200, min_periods=200).mean()

plt.plot(x, y)
plt.plot(a)
plt.plot(b)
plt.savefig("AAPL Stuff")

我在 Jupyter Notebook 中运行。

我希望输出 [1] 是图表的图像,但我得到了错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-18-d97fbde31cef> in <module>
      4 
      5 df = pd.read_html("https://finance.yahoo.com/quote/AAPL/history?period1=1428469200&period2=1554699600&interval=1d&filter=history&frequency=1d")
----> 6 x = df.Date
      7 y = df.Close
      8 

AttributeError: 'list' object has no attribute 'Date'

【问题讨论】:

    标签: python pandas matplotlib plotly


    【解决方案1】:

    数据被放置在一个(单元素)列表中。

    如果你这样做,在read_html 调用之后,它应该可以工作:

    df = df[0]
    

    【讨论】:

    • 嘿,很抱歉回复晚了,我不得不在另一个项目上工作。我现在收到此错误:KeyError: 0,这是什么意思?抱歉,我是 python 新手,我主要在 CAD 工作。谢谢
    【解决方案2】:

    您的意思是从 DataFrame 对象访问日期功能吗? 如果是这样,那就改变:

    python x = df.Datepython x = df['Date']

    python y = df.Closepython y = df['Close']

    编辑:

    另外:python df.plot(x='Date', y='Close', style='o') 可以代替 plt.plot

    【讨论】:

    • 当我尝试时:python x = df.Datepython x = df['Date'] python y = df.Closepython y = df['Close'] 我得到了错误:TypeError: list indices must be integers or slices, not str
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多