【问题标题】:Parse JSON with duplicate key:value pairs to dataframe使用重复的键:值对解析 JSON 到数据框
【发布时间】:2018-08-05 07:43:35
【问题描述】:

我正在使用 Eventful API,它返回一个 JSON,其中包含一组关于事件的键和值。 JSON 的简化版本(删除了我不使用的键:值对)如下:

{'events': {'event': [{'all_day': '0',
    'calendar_count': None,
    'calendars': None,
    'categories': {'category': [
    {'id': 'books', 'name': 'Literary & Books'},
    {'id': 'attractions', 'name': 'Museums & Attractions'},
    {'id': 'community', 'name': 'Neighborhood'}]},
    'title': 'Totally Random Book Club @ Lionel Bowen Library'},
{'all_day': '0',
    'calendar_count': None,
    'calendars': None,
    'categories': {'category': [
    {'id': 'books', 'name': 'Literary & Books'},
    {'id': 'business', 'name': 'business'}]},
    'title': 'ABCs of Business Management'}
                         ]
               }
    }

所以每个 'title' 可以对应多个 'id' key:values 对。我想要做的是能够将此信息放入如下的数据框中(不必完全如下所示,只需要一种将标题分组到多个“id”的方法):

我使用下面的代码尝试了这个,问题是传递的值的形状不相等:

event_json_title = [title['title'] for title in event_json_read['events']['event']]
event_json_id = [name['id'] for cat in event_json_read['events']['event'] for name in cat['categories']['category']]
df = pd.DataFrame({'title':event_json_title},{'id':event_json_id})

我怀疑答案在于一些附加...我只是不确定如何以一种可以将每个“id”分组到“标题”的方式来做到这一点。

【问题讨论】:

    标签: python json beautifulsoup


    【解决方案1】:

    假设响应变量是你调用的API的响应:

    temp = list()    
    for event in response['events']['event']:
      for category in event['categories']['category']:
        category['title'] = event['title'] 
        temp.append(category)
    df = pd.DataFrame(temp).groupby('title').apply(lambda x: ", ".join(x['id']))
    

    【讨论】:

      【解决方案2】:

      这是一种方法。

      例如:

      event_json_title = [{"title": title['title'], "id": ",".join([i["id"] for i in title['categories']['category']])} for title in event_json_read['events']['event']]
      df = pd.DataFrame.from_dict(event_json_title)
      print(df["title"])
      print "---"
      print(df["id"])
      

      输出:

      0    Totally Random Book Club @ Lionel Bowen Library
      1                        ABCs of Business Management
      Name: title, dtype: object
      ---
      0    books,attractions,community
      1                 books,business
      Name: id, dtype: object
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-17
        • 2017-09-01
        • 2013-08-27
        • 1970-01-01
        • 2019-02-20
        相关资源
        最近更新 更多