【发布时间】: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