【问题标题】:Exploding rows with identical nested keys in pandas在熊猫中爆炸具有相同嵌套键的行
【发布时间】:2021-08-03 03:37:23
【问题描述】:

我在 pandas 数据框中的列中有如下数据:

'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 的新手。

【问题讨论】:

    标签: python pandas dataframe parsing explode


    【解决方案1】:
    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}],
    

    【讨论】:

    • 非常感谢,您为一个压力很大的博士生度过了愉快的一天!
    猜你喜欢
    • 2018-06-20
    • 2021-04-06
    • 2018-08-03
    • 2022-01-27
    • 2019-01-15
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多