Python Pandas-读入JSON(并添加ID列)
不确定这个场景的最佳标题,但基本上我有一个JSON输出,我想将其转换为一个df 初始JSON如下所示:Python Pandas-读入JSON(并添加ID列),python,json,pandas,dictionary,Python,Json,Pandas,Dictionary,不确定这个场景的最佳标题,但基本上我有一个JSON输出,我想将其转换为一个df 初始JSON如下所示: data = [{'Balance': 0.0, 'Currency': 'USD', 'Deposit': 0.0, 'Narration': '', 'TransactionDate': '2000-01-01T00:00:00Z', 'TransactionType': 'Opening Balance', 'ValuePortfolioCurrency': 0.
data = [{'Balance': 0.0,
'Currency': 'USD',
'Deposit': 0.0,
'Narration': '',
'TransactionDate': '2000-01-01T00:00:00Z',
'TransactionType': 'Opening Balance',
'ValuePortfolioCurrency': 0.0,
'Withdrawal': 0.0},
{'Balance': 15000.0,
'Currency': 'USD',
'Deposit': 15000.0,
'Narration': 'XYZ',
'TransactionDate': '2010-01-01T00:00:00Z',
'TransactionType': 'Deposit',
'ValuePortfolioCurrency': 15000.0,
'Withdrawal': 0.0},
{'Balance': 13000.0,
'Currency': 'USD',
'Deposit': 0.0,
'Narration': 'ABC',
'TransactionDate': '2010-12-01T00:00:00Z',
'TransactionType': 'Transfer Out',
'ValuePortfolioCurrency': -2000.0,
'Withdrawal': -2000.0}]
我可以轻松地用pd.DataFramedata将其放入df中
df:
但是,我想从JSON的另一个嵌套向整个事务块追加一个ID。现在我可以控制如何添加该ID。。我可以将它添加到列表中,或者使用ID作为键的dict
这可能类似于下面使用1234作为ID的代码段
data = ['1234',[{'Balance': 0.0,
'Currency': 'USD',
'Deposit': 0.0,
'Narration': '',
'TransactionDate': '2000-01-01T00:00:00Z',
'TransactionType': 'Opening Balance',
'ValuePortfolioCurrency': 0.0,
'Withdrawal': 0.0}...]]
或者
因此,我想要的最终输出是为所有内部事务创建一个ID为的列,如下所示,请参见最后一列:
Balance Currency Deposit Narration TransactionDate TransactionType ValuePortfolioCurrency Withdrawal ID
0 0.0 USD 0.0 2000-01-01T00:00:00Z Opening Balance 0.0 0.0 1234
1 15000.0 USD 15000.0 XYZ 2010-01-01T00:00:00Z Deposit 15000.0 0.0 1234
2 13000.0 USD 0.0 ABC 2010-12-01T00:00:00Z Transfer Out -2000.0 -2000.0 1234
我尝试了一些json_规范化的方法,但都没有成功。希望这一切都有意义,谢谢。这里有一个带有虚拟id列表的解决方案。它通过迭代您提供的字典列表来工作,并添加一个名为id的新键:
data = {'1234':[{'Balance': 0.0,
'Currency': 'USD',
'Deposit': 0.0,
'Narration': '',
'TransactionDate': '2000-01-01T00:00:00Z',
'TransactionType': 'Opening Balance',
'ValuePortfolioCurrency': 0.0,
'Withdrawal': 0.0}...]}
Balance Currency Deposit Narration TransactionDate TransactionType ValuePortfolioCurrency Withdrawal ID
0 0.0 USD 0.0 2000-01-01T00:00:00Z Opening Balance 0.0 0.0 1234
1 15000.0 USD 15000.0 XYZ 2010-01-01T00:00:00Z Deposit 15000.0 0.0 1234
2 13000.0 USD 0.0 ABC 2010-12-01T00:00:00Z Transfer Out -2000.0 -2000.0 1234
n = len(data)
ids = ['1234'] * n
for i,j in zip(data, ids):
i["id"] = j
df = pd.DataFrame(data)
print(df)
Balance Currency Deposit Narration TransactionDate TransactionType \
0 0.0 USD 0.0 2000-01-01T00:00:00Z Opening Balance
1 15000.0 USD 15000.0 XYZ 2010-01-01T00:00:00Z Deposit
2 13000.0 USD 0.0 ABC 2010-12-01T00:00:00Z Transfer Out
ValuePortfolioCurrency Withdrawal id
0 0.0 0.0 1234
1 15000.0 0.0 1234
2 -2000.0 -2000.0 1234