python - 在熊猫中爆炸具有相同嵌套键的行
问题描述
我在熊猫数据框中有一列看起来像这样的数据:
'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 的新手。
解决方案
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}],
推荐阅读
- java - 当应用程序没有实例或处于非活动状态时,如何在 java android 应用程序中执行任务
- spring-boot - 编译后没有生成jar文件
- flutter - 如何制作一个在颤动时弹出其他按钮组的按钮?
- slurm - 2 个节点的 SLURM 作业脚本
- php - 我在 laravel 中做测试时运行命令 php artisan test 看到这个错误
- python - 花了很长时间才通过 Telethon 从电报中获取消息
- python - 将 geopandas 边界图添加到 plotly
- python - 如何调整其中包含形状的 tkinter overrideredirect 窗口的大小?
- groovy - Groovy 语言中的断言关键字
- twilio - 使用 Twilio 同时向多个号码发起呼叫