2016-09-20 80 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

我編輯我的問題上面,將是冷靜,如果你可以再看看! –