简体   繁体   English

如何从python中的json编写一个grafana简单的json到表查询

[英]how to write a grafana simple json to table query from a json in python

how to convert that data(json) to pandas Dataframe so that it can populate the "keys" as columns and "values" as rows in a grafana simple json to table dynamically.如何将该数据(json)转换为pandas Dataframe,以便它可以将“键”填充为列,并将“值”填充为grafana简单json中的行以动态显示。 actually, it's not in a perfect array format how do I manipulate it to work as data frame?实际上,它不是完美的数组格式,我该如何操作它以用作数据框? help would be greatly appreciated.帮助将不胜感激。

data = {"name":"john","class":"fifth"}
       {"name":"emma","class":"sixth"}

I want to populate keys as columns and rows as values dynamically no matter how many json's we have.无论我们有多少json,我都想动态地将键填充为列和行作为值。

You could use the pandas.DataFrame.from_dict(data) method.您可以使用pandas.DataFrame.from_dict(data)方法。 Docs 文档

An example could look like this:一个示例可能如下所示:

import pandas as pd
data = [{"name":"john","class":"fifth"},
       {"name":"emma","class":"sixth"}]
df = pd.DataFrame.from_dict(data)

Result:结果:

   class  name
0  fifth  john
1  sixth  emma

In this case data is already a list of dictionaries (I assume this is what you mean in your question).在这种情况下,数据已经是一个字典列表(我认为这就是您在问题中的意思)。 If you have the data in JSON-Strings/Files you can use json.loads(data_string) / json.load(data_file) from the json module .如果您在 JSON-Strings/Files 中有数据,则可以使用json 模块中的json.loads(data_string) / json.load(data_file)

Update更新

For the grafana table data structure like this:对于这样的 grafana 表数据结构:

data = [
  {
    "columns":[
      {"text":"Time","type":"time"},
      {"text":"Country","type":"string"},
      {"text":"Number","type":"number"}
    ],
    "rows":[
      [1234567,"SE",123],
      [1234567,"DE",231],
      [1234567,"US",321]
    ],
    "type":"table"
  }
]

A pandas dataframe can be created:可以创建一个熊猫数据框:

keys = [d['text'] for d in data[0]['columns']]
pd.DataFrame(data=data[0]['rows'], columns=keys)

For a result like:对于这样的结果:

   Time     Country  Number
0  1234567  "SE"     123
1  1234567  "DE"     231
2  1234567  "US"     312

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM