首页 > 解决方案 > 在熊猫中爆炸具有相同嵌套键的行

问题描述

我在熊猫数据框中有一列看起来像这样的数据:

'Column name':    
    [{'Name': Dan Smith, 'Attribute1': 4, 'Attribute2': 10, 'Attribute3': 6}, {'Name': Bob Smith, 'Attribute1': 4, 'Attribute2': 10, 'Attribute3': 6}], 
    
    [{'Name': Shelly Smith, 'Attribute1': 4, 'Attribute2': 10, 'Attribute3': 6}, {'Name': Sam Smith, 'Attribute1': 4, 'Attribute2': 10, 'Attribute3': 6}], 
    
    {'Name': Jane Smith, 'Attribute1': 4, 'Attribute2': 10, 'Attribute3': 6},
     
    [{'Name': Chris Smith, 'Attribute1': 4, 'Attribute2': 10, 'Attribute3': 6}, {'Name': Darryl Smith, 'Attribute1': 4, 'Attribute2': 15, 'Attribute3': 6}], 

公司由 [] 分隔,除非公司只有 1 个观察值(例如本示例中的第 3 个观察值与 Jane Smith)。我的问题是在嵌套键相同时尝试解析嵌套键。我的目标是抓住每家公司价值最高的属性。

我试过了:

 df = df.explode('Column Name')

但是,这无济于事。观察结果与以前相同。经过一些研究,我尝试了以下

from ast import literal_eval
df['Column name'] = df['Column name'].apply(literal_eval)
df = df.explode('Column Name')

但是,当我这样做时,我得到一个“KeyError:0”返回。我发现这个错误是由于第三行这样的情况而发生的,其中该公司只有 1 个观察值。我可以分解我的数据的小样本并获取最高属性并按计划进行。但是,我有 162 万行,因此将样本分成小批量是不明智的。

有没有办法传递 'KeyError:0' 异常?还是有更好的方法可以到达我想去的地方?我是 Python/Pandas 的新手。

标签: pythonpandasdataframeparsingexplode

解决方案


def tolist(x):
    if isinstance(x, dict):
        return [x]
    else:
        return x

df['Column name'] = df['Column name'].apply(literal_eval).apply(tolist)
df = df.explode('Column name')

解释

要使用explode,每一行都必须是一个序列类型(list在这种情况下)。您需要做的第一件事是清理它是单个元素的所有行并将其转换为一个元素的列表

    [{'Name': Jane Smith, 'Attribute1': 4, 'Attribute2': 10, 'Attribute3': 6}],

推荐阅读