TypeError:“ DataFrame”类型的对象不可JSON序列化

时间:2018-08-09 15:08:53

标签: python-3.x postgresql pandas plotly psycopg2

我正在尝试使用从PostgreSQL服务器中获取的一些数据来创建一个绘图图,但是当我尝试进行绘图时,我得到了一个错误:“ TypeError:类型为'DataFrame'的对象不是JSON可序列化的“

这是到目前为止的代码:

import dash
import numpy as np
import pandas as pd
import plotly.offline as py
import plotly.graph_objs as go
import psycopg2 as pg2
import datetime

conn = pg2.connect(database='X',user='X',password=secret)

cur = conn.cursor()

cur.execute("SELECT * FROM times;")
a = cur.fetchall()
str(a)


df = pd.DataFrame([[ij for ij in i] for i in a])
df.to_json()
df.rename(columns={0: "Serial Number", 1: "Status", 2: "Date", 3: "Time", 4: "Number"}, inplace=True);

x = df["Date"]
data = [go.Scatter(
            x=x,
            y=df["Status"])]

layout = go.Layout(title="Server Data Visualization",
                   xaxis = dict(
                   range = [df.head(1),
                            df.tail(1)]),
                    yaxis=dict(title = "Status"))

fig = go.Figure(data = data, layout = layout)
py.plot(fig)

df [“ Date”]是格式为“ 2018-08-03”的日期,而df [“ Status”]是“正常运行时间”或“停机时间”。

有人可以告诉我我做错了什么吗?我试图使该图基本上是从sql server读取的x轴上的日期,然后是y轴上的两个值,分别表示“正常运行时间”或“停机时间”的值。

Traceback (most recent call last):
  File "\\srv31data1\users$\User\Desktop\basic.py", line 37, in <module>
    py.plot(fig)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\plotly\offline\offline.py", line 469, in plot
    '100%', '100%', global_requirejs=False)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\plotly\offline\offline.py", line 184, in _plot_html
    cls=utils.PlotlyJSONEncoder)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\plotly\utils.py", line 161, in encode
    encoded_o = super(PlotlyJSONEncoder, self).encode(o)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\plotly\utils.py", line 229, in default
    return _json.JSONEncoder.default(self, obj)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 180, in default
    o.__class__.__name__)
TypeError: Object of type 'DataFrame' is not JSON serializable

编辑:对不起,忘记发布追溯了!

2 个答案:

答案 0 :(得分:14)

您的df仍然是数据帧,因为您尚未将其分配为json。

   df = df.to_json()

这应该有效。让我知道是否可以。

答案 1 :(得分:1)

df = pd.read_csv(data)
return_data = {
    "status": 1,
    "message": "Raw Data List with pagination",
    "data": {
        "is_header": is_header,
        "head": **json.loads(df.head().to_json())**
    }
}

enter image description here