【问题标题】:Can't plot live data because of dataframe errors由于数据框错误,无法绘制实时数据
【发布时间】:2016-03-12 15:40:47
【问题描述】:

我试图从 Bit Coin 网站绘制实时数据,但出现此错误 'ValueError: 值的长度与索引的长度不匹配'。我无法修复它。我认为这是因为我无法将不同长度的列添加到数据框中。任何人都可以为此提供帮助吗?

感谢您的帮助。

最好的问候,英坦

import matplotlib
matplotlib.use("TkAgg")

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style

import pandas as pd
import numpy as np

import urllib
import json

LARG_FONT =("Verdana", 12)
style.use('ggplot')

f = Figure(figsize = (5,5), dpi=100)
a = f.add_subplot(111)


def animate(i):
    dataLink = "https://btc-e.com/api/3/trades/btc_usd?limit=2000"
    data = urllib.request.urlopen(dataLink)
    data = data.readall().decode("utf-8")
    data = json.loads(data)
    data  = data["btc_usd"]
    data = pd.DataFrame(data)

    buys = data[(data['type']=="bid")]
    buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
    buyDates = (buys["datestamp"]).tolist()


    sells = data[(data['type']=="ask")]
    sells["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
    sellDates = (sells["datestamp"]).tolist()

    a.clear()
    a.plot_date(buyDates, buys["price"])
    a.plot_date(selfDates, sells["price"])


import tkinter as tk
from tkinter import ttk

class RealOptionApp(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        tk.Tk.iconbitmap(self, default='') #Change icon of App
        tk.Tk.wm_title(self, "RealOptionApp")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand= True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames ={}

        for F in (StartPage, PageOne, BTCe_Page):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
            self.show_frame(StartPage)


    def show_frame(self, cont):

        frame=self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label=ttk.Label(self, text="StartPage", font=LARG_FONT)
        label.pack(pady=10, padx=10)

        button1 =ttk.Button(self, text="Agree", command=lambda: controller.show_frame(BTCe_Page))
        button1.pack()


        button2 =ttk.Button(self, text="Disagree", command=quit)
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label=ttk.Label(self, text="PageOne", font=LARG_FONT)
        label.pack(pady=10, padx=10)

        button1 =ttk.Button(self, text="Back to Start Page", command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 =ttk.Button(self, text="Go to BTCe_Page", command=lambda: controller.show_frame(BTCe_Page))
        button2.pack()



class BTCe_Page(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label=ttk.Label(self, text="GraphPage", font=LARG_FONT)
        label.pack(pady=10, padx=10)

        button1 =ttk.Button(self, text="Back to PageOne", command=lambda: controller.show_frame(PageOne))
        button1.pack()

        button2 =ttk.Button(self, text="Back to Start Page", command=lambda: controller.show_frame(StartPage))
        button2.pack()


        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)


app = RealOptionApp()
ani = animation.FuncAnimation(f, animate, interval = 1000)
app.mainloop()

【问题讨论】:

    标签: python pandas matplotlib dataframe urllib2


    【解决方案1】:

    尝试更改以下行:

    购买

    buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
    

    到:

    buys["datestamp"] = pd.to_datetime(buys["timestamp"])
    

    卖出

    sells["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
    

    到:

    sells["datestamp"] = pd.to_datetime(buys["datestamp"])
    

    而且你拼错了一个变量名,所以改一下:

    销售日期

    a.plot_date(selfDates, sells["price"])
    

    到:

    a.plot_date(sellDates, sells["price"])
    

    【讨论】:

    • 感谢 jezrael 和 MaxU
    【解决方案2】:

    我认为你可以让你的问题更简单,因为可能会有更多问题。

    我可以帮助你Pandas
    您可以用于创建和过滤DataFrame 函数read_jsonto_datetime

    如果您需要将列timestamp 转换为date,请使用dt.date

    import pandas as pd
    
    #read json to dataframe and create df from dict column btc_usd
    dataLink = "https://btc-e.com/api/3/trades/btc_usd?limit=2000"
    data = pd.DataFrame([x for x in pd.read_json(dataLink)['btc_usd'] ])
    #column timestamp converted to datetime
    data['timestamp'] = pd.to_datetime(data['timestamp'], unit='s')
    print data.head()
         amount    price       tid           timestamp type
    0  0.020000  410.100  68313536 2016-03-12 16:28:14  ask
    1  0.020000  410.100  68313535 2016-03-12 16:28:14  ask
    2  0.307000  410.492  68313534 2016-03-12 16:28:10  ask
    3  0.060000  410.492  68313533 2016-03-12 16:28:09  bid
    4  0.189918  410.100  68313532 2016-03-12 16:28:08  ask
    
    #filter data
    buys = data[(data['type']=="bid")]
    #get only date (remove time) to list
    buyDates = buys["timestamp"].dt.date.tolist()
    
    sells = data[(data['type']=="ask")]
    #get only date (remove time) to list
    sellDates = sells["timestamp"].dt.date.tolist()
    
    print sells.head()
         amount    price       tid           timestamp type
    0  0.020000  410.100  68313536 2016-03-12 16:28:14  ask
    1  0.020000  410.100  68313535 2016-03-12 16:28:14  ask
    2  0.307000  410.492  68313534 2016-03-12 16:28:10  ask
    4  0.189918  410.100  68313532 2016-03-12 16:28:08  ask
    5  0.010041  410.300  68313531 2016-03-12 16:28:08  ask
    
    print sellDates[:5]
    [datetime.date(2016, 3, 12), datetime.date(2016, 3, 12), datetime.date(2016, 3, 12), datetime.date(2016, 3, 12), datetime.date(2016, 3, 12)]
    

    如果您需要所有Timestamp,则不需要dt.date

    sellDates = sells["timestamp"].tolist()
    buyDates = buys["timestamp"].tolist()
    
    print sellDates[:5]
    [Timestamp('2016-03-12 16:35:58'), Timestamp('2016-03-12 16:35:58'), Timestamp('2016-03-12 16:35:58'), Timestamp('2016-03-12 16:35:58'), Timestamp('2016-03-12 16:35:58')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 2021-03-24
      • 2015-02-04
      • 2021-02-21
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多