我有如下的pandas DataFrame,包含2列:Address和Transactions。
Address Transactions
0 0x88aDa02f6fCE2F1A835567B4999D62a7ebb70367 [{'type': 'outflow', 'amount': '250,000 VSO'}, {'type': inflow, 'amount': 100,000}]
1 0x00979Bd14bD5Eb5c424c5478d3BF4b6E9212bA7d [{'type': 'inflow', 'amount': '9.1283802424254'}, {'type': inflow, 'amount': 100,000}]
2 0x5852346d9dC3d64d81dc82fdddd5Cc1211157cD5 [{'type': 'outflow', 'amount': '7,200 VSO'}, {'type': inflow, 'amount': 100,000}]
每个地址有多个事务,一个地址的所有事务都用一个包含一个字典的列表来表示。
每个字典有两个键和两个值:type和amount。
创建上述表的代码如下:df_dict = pd.DataFrame(dict_all_txs_all_addresses.items(), columns=['Address', 'Transactions'])
我想做的:
我想创建一个多索引(也许是不必要的?)的表,它看起来像这样:
Address Type Amount
0 0x88aDa02f6fCE2F1A835567B4999D62a7ebb70367 outflow 250,000 VSO
inflow 100,000 VSO
1 0x00979Bd14bD5Eb5c424c5478d3BF4b6E9212bA7d inflow 330,000 VSO
inflow 150,000 VSO'
它在不同的行中显示每个事务,同时只维护一个地址。注意,这个模型表有3列。
也许这可以解决使用df.groupby()而不是多索引df?
下面是一个字典的例子,便于阅读和操作:
dict_all_txs_all_addresses = {
"0x00979Bd14bD5Eb5c424c5478d3BF4b6E9212bA7d": [
{
"amount": "330,000 VSO",
"type": "inflow"
},
{
"amount": "150,000 VSO",
"type": "inflow"
}
],
"0x88aDa02f6fCE2F1A833cd9B4999D62a7ebb70367": [
{
"amount": "250,000 VSO",
"type": "outflow"
},
{
"amount": "100,000 VSO",
"type": "inflow"
}
]
}
我们可以使用pd.json_normalize
在这里得到一个整洁的格式,这是可行的:
df = df.explode("Transactions", ignore_index=True)
df = pd.concat([df, pd.json_normalize(df.pop("Transactions"))], axis=1)
Address amount type
0 0x00979Bd14bD5Eb5c424c5478d3BF4b6E9212bA7d 330,000 VSO inflow
1 0x00979Bd14bD5Eb5c424c5478d3BF4b6E9212bA7d 150,000 VSO inflow
2 0x88aDa02f6fCE2F1A833cd9B4999D62a7ebb70367 250,000 VSO outflow
3 0x88aDa02f6fCE2F1A833cd9B4999D62a7ebb70367 100,000 VSO inflow
爆炸Transactions
列,然后使用apply(pd.Series)
技巧通过键将其扩展为多个列:
(df.set_index('Address')
.explode('Transactions')
.Transactions
.apply(pd.Series)
.set_index('type', append=True))
amount
Address type
0x00979Bd14bD5Eb5c424c5478d3BF4b6E9212bA7d inflow 330,000 VSO
inflow 150,000 VSO
0x88aDa02f6fCE2F1A833cd9B4999D62a7ebb70367 outflow 250,000 VSO
inflow 100,000 VSO
如果您需要将所有列显示为普通列而不是索引,请使用reset_index
而不是set_index
:
df.set_index('Address').explode('Transactions').Transactions.apply(pd.Series).reset_index()
Address amount type
0 0x00979Bd14bD5Eb5c424c5478d3BF4b6E9212bA7d 330,000 VSO inflow
1 0x00979Bd14bD5Eb5c424c5478d3BF4b6E9212bA7d 150,000 VSO inflow
2 0x88aDa02f6fCE2F1A833cd9B4999D62a7ebb70367 250,000 VSO outflow
3 0x88aDa02f6fCE2F1A833cd9B4999D62a7ebb70367 100,000 VSO inflow