2016-09-20 82 views
2

我需要你的帮助,将多维字典转换为熊猫数据框。我从一个JSON文件中获取字典,我从API调用(Shopify)中检索该字典。API调用 - 多维嵌套字典到熊猫数据框

response = requests.get("URL", auth=("ID","KEY")) 
data = json.loads(response.text) 

“数据”字典看起来如下:

{'orders': [{'created_at': '2016-09-20T22:04:49+02:00', 
      'email': '[email protected]', 
      'id': 4314127108, 
      'line_items': [{'destination_location': 
             {'address1': 'Teststreet 12', 
             'address2': '', 
             'city': 'Berlin', 
             'country_code': 'DE', 
             'id': 2383331012, 
             'name': 'Test Test', 
             'zip': '10117'}, 
          'gift_card': False, 
          'name': 'Blueberry Cup'}] 
}]} 

在这种情况下,词典有4种尺寸和我想的字典转换成大熊猫数据帧。我尝试了从json_normalize()到pandas.DataFrame.from_dict()的所有事情,但是我没有设法找到任何地方。当我尝试将dict转换为df时,我得到包含列表列的列。

有谁知道如何解决这个问题?

感谢

编辑:

谢谢@piRSquared。您的解决方案正常工作但是,如果订单中有另一种产品,您如何解决这个问题?因为它确实有效。 2个产品的订单的JSON回应如下(目标是有第二个行具有相同的“created_at”,“电子邮件”等列。):

{'orders': [{'created_at': '2016-09-20T22:04:49+02:00', 
      'email': '[email protected]', 
      'id': 4314127108, 
      'line_items': [{'destination_location': 
             {'address1': 'Teststreet 12', 
             'address2': '', 
             'city': 'Berlin', 
             'country_code': 'DE', 
             'id': 2383331012, 
             'name': 'Test Test', 
             'zip': '10117'}, 
          'gift_card': False, 
          'name': 'Blueberry Cup'}, 
          {'destination_location': 
             {'address1': 'Teststreet 12', 
             'address2': '', 
             'city': 'Berlin', 
             'country_code': 'DE', 
             'id': 2383331012, 
             'name': 'Test Test', 
             'zip': '10117'}, 
          'gift_card': False, 
          'name': 'Strawberry Cup'}] 
}]} 

那么到底DF应该是所有销售产品都是按行排列。谢谢,我非常感谢你的帮助!

回答

0

有很多方法可以做到这一点。这只是我决定去做的一种方式。你需要探索你想如何看待这个代表,然后找出如何到达那里。

df = pd.DataFrame(data['orders']) 

df1 = df.line_items.str[0].apply(pd.Series) 

df2 = df1.destination_location.apply(pd.Series) 

pd.concat([df.drop('line_items', 1), df1.drop('destination_location', 1), df2], 
      axis=1, keys=['', 'line_items', 'destination_location']) 

enter image description here

+0

我编辑我的问题上面,将是冷静,如果你可以再看看! –