熊猫-在数据框的列内扩展嵌套的json数组

Eri*_* D. 8 python json pandas

我有一个json数据(来自mongodb),其中包含数千条记录(因此是json对象的数组/列表),每个对象的结构如下所示:

{
   "id":1,
   "first_name":"Mead",
   "last_name":"Lantaph",
   "email":"mlantaph0@opensource.org",
   "gender":"Male",
   "ip_address":"231.126.209.31",
   "nested_array_to_expand":[
      {
         "property":"Quaxo",
         "json_obj":{
            "prop1":"Chevrolet",
            "prop2":"Mercy Streets"
         }
      },
      {
         "property":"Blogpad",
         "json_obj":{
            "prop1":"Hyundai",
            "prop2":"Flashback"
         }
      },
      {
         "property":"Yabox",
         "json_obj":{
            "prop1":"Nissan",
            "prop2":"Welcome Mr. Marshall (Bienvenido Mister Marshall)"
         }
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

当加载到数据帧中时,“ nested_array_to_expand”是一个包含json的字符串(我在加载过程中确实使用了“ json_normalize”)。预期的结果是获得一个带有3行(给定上面的示例)和一个嵌套对象的新列的数据框,如下所示:

index   email first_name gender  id      ip_address last_name  \
0  mlantaph0@opensource.org       Mead   Male   1  231.126.209.31   Lantaph   
1  mlantaph0@opensource.org       Mead   Male   1  231.126.209.31   Lantaph   
2  mlantaph0@opensource.org       Mead   Male   1  231.126.209.31   Lantaph   

  test.name                                      test.obj.ahah test.obj.buzz  
0     Quaxo                                      Mercy Streets     Chevrolet  
1   Blogpad                                          Flashback       Hyundai  
2     Yabox  Welcome Mr. Marshall (Bienvenido Mister Marshall)        Nissan  
Run Code Online (Sandbox Code Playgroud)

我可以使用以下功能获得该结果,但是它非常慢(1k记录大约2s),因此我想改进现有代码或寻找一种完全不同的方法来获得该结果。

def expand_field(field, df, parent_id='id'):
    all_sub = pd.DataFrame()
    # we need an id per row to be able to merge back dataframes
    # if no id, then we will create one based on index of rows
    if parent_id not in df:
        df[parent_id] = df.index

    # go through all rows and create a new dataframe with values
    for i, row in df.iterrows():
        try:
            sub = json_normalize(df[field].values[i])
            sub = sub.add_prefix(field + '.')
            sub['parent_id'] = row[parent_id]
            all_sub = all_sub.append(sub)
        except:
            print('crash')
            pass
    df = pd.merge(df, all_sub, left_on=parent_id, right_on='parent_id', how='left')
    #remove old columns
    del df["parent_id"]
    del df[field]
    #return expanded dataframe
    return df
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助。

=====编辑评论====

从mongodb加载的数据是对象数组。我用以下代码加载它:

data = json.loads(my_json_string)
df = json_normalize(data)
Run Code Online (Sandbox Code Playgroud)

输出给我一个以df [“ nested_array_to_expand”]作为dtype对象的数据框(字符串)

0    [{'property': 'Quaxo', 'json_obj': {'prop1': '...
Name: nested_array_to_expand, dtype: object
Run Code Online (Sandbox Code Playgroud)

Rom*_*ain 8

我建议使用一个有趣的答案,pandas.io.json.json_normalize请参阅文档。我用它来扩展嵌套的json-也许有更好的方法,但是您绝对应该考虑使用此功能。然后,您只需要根据需要重命名列。

import io
from pandas.io.json import json_normalize

# Loading the json string into a structure
json_dict = json.load(io.StringIO(json_str))

df = pd.concat([pd.DataFrame(json_dict), 
                json_normalize(json_dict['nested_array_to_expand'])], 
                axis=1).drop('nested_array_to_expand', 1)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 嗨,罗曼,您好,代码无法在我的设置中运行,因为我从json中获得了字典列表,而不是直接获取字典。 (2认同)

Gab*_*air 6

下面的代码就是你想要的。您可以使用 python 的内置列表函数展开嵌套列表,并将其作为新数据帧传递。 pd.DataFrame(list(json_dict['nested_col']))

您可能需要对此进行多次迭代,具体取决于数据的嵌套方式。

from pandas.io.json import json_normalize


df= pd.concat([pd.DataFrame(json_dict), pd.DataFrame(list(json_dict['nested_array_to_expand']))], axis=1).drop('nested_array_to_expand', 1)
Run Code Online (Sandbox Code Playgroud)