如何将pandas数据框转换为嵌套的JSON格式

3

现在有一个数据框包含笔记本电脑信息,目标是将数据转换为嵌套的JSON格式。由于笔记本电脑的品牌、价格和重量是相关信息,因此希望将它们分组到笔记本电脑字段下面。如何转换数据框的任何指针将不胜感激。

数据框

enter image description here

目标JSON结构

enter image description here


类似的问题和答案可以在这里找到: https://dev59.com/UVkS5IYBdhLWcg3wCCbf - Ena
请勿发布图片。在SO上不鼓励使用图片。请花时间阅读how-to-make-good-reproducible-pandas-examples - Shubham Sharma
1个回答

3

考虑 df:

In [2729]: df = pd.DataFrame({'Store code':[1, 12, 132], 'Laptop brand':['Lenovo', 'Apple', 'HP'], 'Laptop price':[1000, 2000, 1200], 'Laptop weight':[1.2, 1.5, 1.4], 'star':[3, 5, 4]})

In [2730]: df
Out[2730]: 
   Store code Laptop brand  Laptop price  Laptop weight  star
0           1       Lenovo          1000            1.2     3
1          12        Apple          2000            1.5     5
2         132           HP          1200            1.4     4

使用 df._to_dict 方法, 并设置参数 orient='records':

In [2734]: x = df.to_dict('records') # Create a list of dicts from df
In [2738]: l = [] # Empty list for storing your output

In [2763]: for i in x: # Iterate every item in list of dicts
      ...:     d = {}
      ...:     d1 = {}
      ...:     for k,v in i.items(): # Iterate each individual dict
      ...:         if 'Laptop' in k: # Check if word `Laptop` is present in key 
      ...:             d1[k] = v     # If yes, create a separate dict for all laptop keys
      ...:         else:
      ...:             d[k] = v      
      ...:     d['Laptop'] = [d1]    # Add another key `Laptop` which holds a `list` of dicts of Laptop
      ...:     l.append(d)           # Append this dict in list
      ...: 

输出:

In [2774]: print(json.dumps(l, indent=2))
[
  {
    "Store code": 1,
    "star": 3,
    "Laptop": [
      {
        "Laptop brand": "Lenovo",
        "Laptop price": 1000,
        "Laptop weight": 1.2
      }
    ]
  },
  {
    "Store code": 12,
    "star": 5,
    "Laptop": [
      {
        "Laptop brand": "Apple",
        "Laptop price": 2000,
        "Laptop weight": 1.5
      }
    ]
  },
  {
    "Store code": 132,
    "star": 4,
    "Laptop": [
      {
        "Laptop brand": "HP",
        "Laptop price": 1200,
        "Laptop weight": 1.4
      }
    ]
  }
]

谢谢,如果您能添加一些解释,那就太好了。 - Codezzz
不客气。我在我的答案中添加了注释来解释。请看一下。 - Mayank Porwal
谢谢。我可以问一下您是否已经检查了关键字中是否包含单词“笔记本电脑”,如果关键字不包含“笔记本电脑”这个词,是否有办法将该关键字包含到另一个字典中? - Codezzz
如果键不包含单词“Laptop”,它将以相同的方式存储,例如“Store code”和“star”。 - Mayank Porwal
可以的。在这种情况下,您需要调整if语句。 - Mayank Porwal
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接