【问题标题】:generate a new Dataframe from mongodb collection nested array从 mongodb 集合嵌套数组生成一个新的 Dataframe
【发布时间】:2022-01-03 01:48:56
【问题描述】:

我正在尝试从 mongodb 集合生成一个新的数据框,目标是创建一个仅代表“事件”列的新 df:

例如:

{
    "_id" : 1641008579,
    "status" : "init",
    "description" : "Test",
    "attachment" : null,
    "start" : "08:00",
    "user" : "Jenny",
    "timestamp" : ISODate("2022-01-01T04:43:11.380Z"),
    "events" : [ 
        {
            "id" : 1641008580,
            "status" : "start",
            "description" : "First Event",
            "user" : "Jenny",
            "timestamp" : ISODate("2022-01-01T04:43:11.380Z")
        }, 
        {
            "id" : 1641008581,
            "status" : "progress",
            "description" : "Middle of the Event",
            "user" : "Joe",
            "timestamp" : ISODate("2022-01-01T05:43:11.380Z")
        }, 
        {
            "id" : 1641008582,
            "status" : "end",
            "description" : "Last Event",
            "user" : "Alain",
            "timestamp" : ISODate("2022-01-01T06:43:11.380Z")
        }
    ]
}

知道如何开始一种方法以获得以下结果吗?

event_df 应该如下所示:

    id          status      description             user    timestamp
0   1641008580  start       First Event             Jenny   "2022-01-01T04:43:11.380Z"
1   1641008581  progress    Middle of the Event     Joe     "2022-01-01T05:43:11.380Z"
2   1641008582  end         Last Event              Alain   "2022-01-01T06:43:11.380Z"

/K

【问题讨论】:

    标签: python arrays mongodb dataframe nested


    【解决方案1】:

    Pandas 的pandas.json_normalize 方法在这里完美运行,它将“将半结构化 JSON 数据标准化为平面表”。返回一个DataFrame。

    API 参考 -> pandas.json_normalize

    import json
    import pandas as pd
    
    with open('mongo.json') as json_file: # retrieve the json file
        data = json.load(json_file) # deserialize the json file to a dict 
        events_df = pd.json_normalize(data['events']) # normalize and create a dataframe 
        print(events_df)
    

    【讨论】:

    • 感谢 Kwaku 的建议,但它没有帮助,我只是编辑并添加了确切的需要。
    • 只是修复一种方法,老实说我不喜欢它,但它可以正常工作。
    • @koul 我不确定你在问什么。另外,您打开的文件名或目录是什么?
    【解决方案2】:

    这是加载集合后的一个函数:

    def set_event_2_df(last_situation):
        for doc in last_situation:
            for k, v in doc.items():
                try:
                    if k == 'events':
                        for i, e in enumerate(doc['events']):
                            new_row = {
                                'id': str(doc['events'][i]['id']),
                                'status': doc['events'][i]['status'],
                                'description': doc['events'][i]['description'],
                                'user': doc['events'][i]['user'],
                                'timestamp': doc['events'][i]['timestamp']
                            }
                            df_event = df_event.append(new_row, ignore_index=True)
                except Exception as e:
                    print('EXP - {}'.format(e))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 2018-03-06
      • 1970-01-01
      • 2021-12-05
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多