【问题标题】:Sort and Select Top 5 JSON values排序并选择前 5 个 JSON 值
【发布时间】:2021-06-04 22:11:19
【问题描述】:

我有两个问题,正在寻找解决方法的线索。

我有一个格式如下的 json 文件:

{
    "code": 2000,
    "data": {
        "1": {
            "attribute1": 40,
            "attribute2": 1.4,
            "attribute3": 5.2,
            "attribute4": 124
            "attribute5": "65.53%"
        },        
        "94": {
            "attribute1": 10,
            "attribute2": 4.4,
            "attribute3": 2.2,
            "attribute4": 12
            "attribute5": "45.53%"
        },
        "96": {
            "attribute1": 17,
            "attribute2": 9.64,
            "attribute3": 5.2,
            "attribute4": 62
            "attribute5": "51.53%"
        }
    },
    "message": "SUCCESS"
}

我的目标是:

  1. 我首先想按任何个属性对数据进行排序。
  2. 大约有 100 个,我想抢前 5 个(取决于它们的排序方式),然后...
  3. 在表格中输出数据,例如:
These are sorted by: attribute5
---
attribute1 | attribute2 | attribute3 | attribute4 | attribute5
40 |1.4 |5.2|124|65.53%
17 |9.64|5.2|62 |51.53%
10 |4.4 |2.2|12 |45.53%

*同样,上面的attribute5是一个字符串值

诚然,我在这里的知识非常有限。 我试图模仿这里使用的方法: python sort list of json by value

我设法打开该文件,我可以从示例行中提取键值:

import json

jsonfile = path-to-my-file.json

with open(jsonfile) as j:
  data=json.load(j)
  k = data["data"]["1"].keys()
  print(k)

total=data["data"]
for row in total:
    v = data["data"][str(row)].values()
    print(v)

这个输出:

dict_keys(['attribute1', 'attribute2', 'attribute3', 'attribute4', 'attribute5'])
dict_values([1, 40, 1.4, 5.2, 124, '65.53%'])
dict_values([94, 10, 4.4, 2.2, 12, '45.53%'])
dict_values([96, 17, 9.64, 5.2, 62, '51.53%'])

我们将不胜感激。

谢谢!

【问题讨论】:

    标签: json python-3.x


    【解决方案1】:

    如果你不介意使用pandas,你可以这样做

    import pandas as pd
    rows = [v for k,v in data["data"].items()]
    
    df = pd.DataFrame(rows)
    
    # then to get the top 5 values by attribute can choose either ascending
    # or descending with the ascending keyword and head prints the top 5 rows
    
    df.sort_values('attribute1', ascending=True).head()
    

    这将允许您随时按所需的任何属性进行排序并打印出表格。

    这将产生这样的输出,具体取决于您的排序方式

       attribute1  attribute2  attribute3  attribute4 attribute5
    0          40        1.40         5.2         124     65.53%
    1          10        4.40         2.2          12     45.53%
    2          17        9.64         5.2          62     51.53%
    

    【讨论】:

    • 这符合所有目标,而且非常简单。我不熟悉熊猫库。如果我要定期使用 JSON 数据,pandas 是最可持续/最直接的方法吗?
    • @p3hndrx 这通常取决于在 python 中从各种数据结构中创建表格数据(以及更多)的最佳方式。如果您打算在获得数据后对数据进行任何类型的数据分析,那么我肯定会建议使用pandas,因为它就是为此而设计的
    【解决方案2】:

    如果您不想使用 pandas,我将把这个答案留在这里,但 @MatthewBarlowe 的答案不那么复杂,我建议这样做。

    对于按特定属性进行排序,这应该有效:

    import json
    
    SORT_BY = "attribute4"
    
    with open("test.json") as j:
        data = json.load(j)
    
    items = data["data"]
    sorted_keys = list(sorted(items, key=lambda key: items[key][SORT_BY], reverse=True))
    

    现在,sorted_keys 是一个按属性排序的键列表。

    然后,为了将其打印为表格,我使用了tabulate 库。我的最终代码如下所示:

    from tabulate import tabulate
    import json
    
    SORT_BY = "attribute4"
    
    with open("test.json") as j:
        data = json.load(j)
    
    items = data["data"]
    sorted_keys = list(sorted(items, key=lambda key: items[key][SORT_BY], reverse=True))
    
    print(f"\nSorted by: {SORT_BY}")
    print(
        tabulate(
            [
                [sorted_keys[i], *items[sorted_keys[i]].values()]
                for i, _ in enumerate(items)
            ],
            headers=["Column", *items["1"].keys()],
        )
    )
    

    当按'attribute5'排序时,输出:

    Sorted by: attribute5
      Column    attribute1    attribute2    attribute3    attribute4  attribute5
    --------  ------------  ------------  ------------  ------------  ------------
           1            40          1.4            5.2           124  65.53%
          96            17          9.64           5.2            62  51.53%
          94            10          4.4            2.2            12  45.53%
    

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 2020-08-22
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多