使用python从嵌套字典创建数据框

时间:2020-05-19 12:10:19

标签: python-3.x pandas

以下是我可以使用的json数据

{
  "status": "success",
  "message": "Transactions Details",
  "TxnArray": [    
    {
      "transactionAmount": {"0": 3500},
      "createdAt": {"0": "17/04/2020"}
    },    
    {
      "transactionAmount": {"1": 4500},
      "createdAt": {"1": "19/04/2020"}
    }
  ]
}

想要像上面的熊猫Dataframe那样转换以上数据

      transactionAmount createdAt
    0 3500               17/4/2020
    1 4500               19/4/2020

3 个答案:

答案 0 :(得分:1)

更紧凑的方法:

import pandas as pd

df = pd.DataFrame([
    {k: v[str(i)] for k, v in list_item.items()} for i, list_item in enumerate(json_data['TxnArray'])
])

答案 1 :(得分:1)

一种略有不同但紧凑的方法,

pd.concat(pd.DataFrame.from_dict(d) for d in data['TxnArray'])

答案 2 :(得分:0)

import pandas as pd
import json

json_str = json.loads('''{
  "status": "success",
  "message": "Transactions Details",
  "TxnArray": [    
    {
      "transactionAmount": {"0": 3500},
      "createdAt": {"0": "17/04/2020"}
    },    
    {
      "transactionAmount": {"1": 4500},
      "createdAt": {"1": "19/04/2020"}
    }
  ]
}''')

df = pd.DataFrame(json_str['TxnArray'])

enter image description here

def clean_function(x):
    return list(x.values())[0]

df = df.applymap(lambda x: clean_function(x))

enter image description here