首页 > 解决方案 > json_normalize 的替代方法,用于展平字典中的列表

问题描述

我有一本字典,其中包含一个需要展平到 0 级的列表。

目前,我正在使用json_normalize,但是,经过几天的研究,我发现它不处理列表并将其保留在一列中。

是否有另一种方法来展平字典和列表?或者是通过创建函数的唯一可能解决方案?

{ 
    "_id" : 1, 
    "active" : false,  
    "labelId" : [
        6422
    ],  
    "level" : [
        {
            "active" : true, 
            "level" : 3, 
            "actions" : [
                {
                    "active" : true, 
                    "description" : "Testing."
                }
            ]
          } 
       ]
  }

电流输出: 在此处输入图像描述

预期输出: 在此处输入图像描述

标签: pythonjsonpandasdictionary

解决方案


您可以使用json_normalise() explode()apply(pd.Series)

js = {'_id': 1,
 'active': False,
 'labelId': [6422],
 'level': [{'active': True,
   'level': 3,
   'actions': [{'active': True, 'description': 'Testing.'}]}]}

df = pd.json_normalize(js).explode("labelId").explode("level")
df = df.join(df["level"].apply(pd.Series), rsuffix="_l2").explode("actions")
df = df.join(df["actions"].apply(pd.Series), rsuffix="_l3")
print(df.drop(columns=["level","actions"]).to_string())

输出

   _id  active labelId  active_l2  level_l2  active_l3 description
0    1   False    6422       True         3       True    Testing.

重命名前缀

js = {'_id': 1,
 'active': False,
 'labelId': [6422],
 'level': [{'active': True,
   'level': 3,
   'actions': [{'active': True, 'description': 'Testing.'}]}]}

df = pd.json_normalize(js).explode("labelId").explode("level")
df = df.join(df["level"].apply(pd.Series), rsuffix="_l2").explode("actions")
df = df.join(df["actions"].apply(pd.Series), rsuffix="_l3")
df = df.drop(columns=["level","actions"])
df.rename(columns={c:f"{c.split('_')[1]}_{c.split('_')[0]}" for c in df.columns if "_" in c})

推荐阅读