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

Python Pandas:嵌套字典转DataFrame时去除索引列的方法

移除DataFrame转换后的自定义索引列

原始数据与问题

嵌套字典数据

data = {
    "policy": {
        "1": {
            "ID": "ML_0",
            "URL": "www.a.com",
            "Text": "my name is Martin and here is my code"
        },
        "2": {
            "ID": "ML_1",
            "URL": "www.b.com",
            "Text": "my name is Mikal and here is my code"
        }
    }
}

原转换代码

for policies in data['policy']:
    new = pd.DataFrame.from_dict(data['policy'], orient='index')

转换后结果(含不需要的索引列)

ID      URL         Text
1   ML_0    www.a.com   my name is Martin and here is my code
2   ML_1    www.b.com   my name is Mikal and here is my code

需求:移除带有数字1、2的索引列,只保留ID、URL、Text三列数据。


解决方法

方法1:转换后重置索引并丢弃原索引

去掉无意义的for循环(循环会重复赋值new,对结果无影响),直接在转换代码后添加reset_index(drop=True):

new = pd.DataFrame.from_dict(data['policy'], orient='index').reset_index(drop=True)

执行后结果:

ID      URL         Text
0  ML_0  www.a.com  my name is Martin and here is my code
1  ML_1  www.b.com  my name is Mikal and here is my code

drop=True参数会直接丢弃原自定义索引列,生成默认的0开始序列索引。

方法2:直接从字典值构建DataFrame

跳过原字典的键("1"、"2"),直接取子字典的值创建DataFrame,代码更简洁:

new = pd.DataFrame(data['policy'].values())

该方式会自动将每个子字典作为一行数据,生成默认索引,结果与方法1一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:57:17