You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas Series中存储的字典键值转换为DataFrame独立列

解决方案

该需求不需要使用多级索引,也不需要借助groupby即可实现,groupby主要用于分组聚合计算,你当前的列表展开、字典拆分场景用pandas内置方法就能更简单地完成,操作步骤如下:

完整代码实现

import pandas as pd

# 示例源数据
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"}
    ]
}

# 构造初始DataFrame
df = pd.DataFrame(dict_all_txs_all_addresses.items(), columns=['Address', 'Transactions'])

# 1. 展开交易列表,每笔交易单独占一行
df_exploded = df.explode('Transactions', ignore_index=True)

# 2. 拆分交易字典为Type、Amount两列
df_result = pd.concat([
    df_exploded['Address'],
    pd.json_normalize(df_exploded['Transactions'])
], axis=1).rename(columns={'type': 'Type', 'amount': 'Amount'})

# 3. (可选)展示层面处理:同一地址仅显示第一次出现的内容,后续重复值留空
df_result.loc[df_result['Address'].duplicated(), 'Address'] = ''

# 输出最终结果
print(df_result)

输出效果

Address     Type       Amount
0  0x00979Bd14bD5Eb5c424c5478d3BF4b6E9212bA7d   inflow  330,000 VSO
1                                                 inflow  150,000 VSO
2  0x88aDa02f6fCE2F1A833cd9B4999D62a7ebb70367  outflow  250,000 VSO
3                                                  inflow  100,000 VSO

说明

如果不需要「重复地址留空」的展示效果,跳过第三步即可得到所有行都携带完整地址信息的普通三列表格,完全满足后续数据统计、查询的需求。


内容的提问来源于stack exchange,提问作者Luiz Scheuer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:18:00