Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

python - How to implement a table with json type data in Plotly using the "json" module?

Here is my code using Pandas:

import plotly.graph_objects as go
import pandas as pd

iris_data = pd.read_json("iris.json")

fig = go.Figure(data=[go.Table(
    header=dict(values=list(iris_data.columns),
                fill_color='paleturquoise',
                align='left'),
    cells=dict(values=[iris_data.UserName, iris_data.Email, iris_data.IP, iris_data.DataDo??czenia, iris_data.LiczbaUrz?dzeń, iris_data.CzyAdmin],
               fill_color='lavender',
               align='left'))
])

fig.show()

It does work nicely, but it is very important that I use the standard "json" python module instead of Pandas here. How can I do that?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Depending on how you read your json data, you might have to change the 'data' object. I took the file exactly as presented in pastebin. Essentially, I just used list comprehension to pull the individual columns and headers from the first json object.

There's probably a more elegant (read: more concise) way to write the list comprehension for multiple lists, but this shows exactly what is happening for each column.

with open('iris.json', 'rb') as f:
    data = json.loads(f.read().decode('utf-8'))['iris_data']

headers = list(data[0].keys())

users = [d['UserName'] for d in data]
emails =  [d['Email'] for d in data]
ips =  [d['IP'] for d in data]
dola =  [d['DataDolaczenia'] for d in data]
licz =  [d['LiczbaUrzadzen'] for d in data]
czya = [d['CzyAdmin'] for d in data]

cells = [users, emails, ips, dola, licz, czya]
fig = go.Figure(data=[go.Table(
    header=dict(values=headers,
                fill_color='paleturquoise',
                align='left'),
    cells=dict(values=cells,
               fill_color='lavender',
               align='left'))
])

fig.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...