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

af7jpaap  于 2023-08-04  发布在  PostgreSQL
关注(0)|答案(2)|浏览(136)

我试图用我从PostgreSQL服务器获得的一些数据创建一个plotly图,但当我尝试绘制图形时,我得到一个错误:“类型错误:“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”]是“Uptime”或“Downtime”。
有人能告诉我我做错了什么吗?我试图让这个图表基本上是x轴上的日期从sql服务器读取,然后在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


编辑:对不起,忘了发布traceback!

o3imoua4

o3imoua41#

您的df仍然是一个 Dataframe ,因为您没有将其分配为json。

df = df.to_json()

字符串
这个应该能用如果没有就告诉我。

hxzsmxv2

hxzsmxv22#

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())**
    }
}

字符串


的数据

相关问题