簡體   English   中英

將嵌套的 json 轉換為 Python 中的 pandas 數據幀

[英]Converting nested json into a pandas data frame in Python

我在 JSON 中有一個嵌套數據框。 我可以將未嵌套的數據框轉換為 pandas 數據框。

我遇到的問題是當數據幀有多個級別時,我需要為每個 json 條目編寫獨立的記錄。

{
  'type': 'text1',
  'key': ['key1'],
  
},  
{
  'type': 'text2',
  'key': ['key1', 'key2'], 
}, 
 'type': 'text3',
 'key': 'key', 
}

我使用以下代碼將其寫入數據幀。

 df = pd.DataFrame.from_dict(json)

在此處輸入圖像描述

不幸的是,對於每個條目,我都必須包含一個記錄。 因此,如果 key 在數組中有 2 個元素,則需要創建 2 個條目。 並且將創建一個附加列(鍵索引)。 所以我想要得到的是類似於下面的東西。

在此處輸入圖像描述

任何幫助將不勝感激,因為我已經堅持了一段時間!

使用explode

json = [{'type': 'text1', 'key': ['key1']},
        {'type': 'text2', 'key': ['key1', 'key2']},
        {'type': 'text3', 'key': 'key'}]

df = pd.DataFrame(json).explode('key') \
       .assign(key_index=lambda x: x.groupby(level=0).cumcount())
print(df)

# Output
    type   key  key_index
0  text1  key1          0
1  text2  key1          0
1  text2  key2          1
2  text3   key          0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM