python - 在 python 中过滤或分组数据的更好方法
问题描述
我对 python 完全陌生,并且努力知道如何以更好的方式过滤或分组我的数据。让我给出上下文。我正在使用Django
andcursor
进行复杂的查询。从查询中获得结果后,我想以我的方式对数据进行分组:
# Some query gives me sorted data (in DESC order)
# Query already grouped data by state, item and distance
rows = cursor.fetchall()
我检索的数据如下所示:
|-----|-------|---------|---------------|
|state| item | distance|selling_percent|
|-----|-------|---------|---------------|
| A | item1 | 107 | 55 |
| A | item2 | 20 | 45 |
| A | item3 | 65 | 40 |
| B | item4 | 88 | 30 |
| B | item2 | 32 | 25 |
| B | item1 | 100 | 20 |
| C | item2 | 170 | 10 |
| C | item3 | 184 | 5 |
| C | item4 | 1 | 2 |
|-----|-------|---------|---------------|
我想要的结果是通过以下步骤:
- 创建新的空白列表(现在称为结果)
- 从第一行开始,检查
state
结果中是否已经存在的行。如果没有,检查item
结果中是否存在。如果没有,则将该行推入结果。 - 如果列表中存在状态或行,则跳过该行
- 填充结果后,对结果列表进行排序
distance
最终结果将是这样的:
|-----|-------|---------|---------------|
|state| item | distance|selling_percent|
|-----|-------|---------|---------------|
| A | item1 | 107 | 55 |
| B | item4 | 88 | 30 |
| C | item2 | 170 | 10 |
|-----|-------|---------|---------------|
它看起来很简单,但我真的很想知道好的方法。目前我正在这样做:
d = defaultdict(dict)
for col, row in zip(cursor.description, rows):
state = row[0]
item = row[1]
distance = row[2]
selling_percent = row[3]
# If state or item exists, skip row
if (state in d) | (item in d[state]):
continue
d[state][item] = {
'distance': distance,
'selling_percent': selling_percent,
}
result = []
# d contains nested dictionary, we want is list of straight dictionary
for state in d:
for item in d[state]:
result.append({
'state': state,
'item': item,
**d[state][item]
})
# sort final result by distance
result = sorted(result, key=lambda k: k['distance'])
我找到了一些不错的库,例如numpy
orpandas
但我发现它在这里可能没用。我在这里发布问题以了解这种逻辑的更好方法。
我会很感激一些帮助!
解决方案
推荐阅读
- c++ - 我的程序随着时间的推移而变慢,我不知道为什么。内存泄漏?
- minecraft - 如何使用 MakeCode 在 Minecraft 中放置半块板
- c# - 使用 Viewbag 绑定模型动态 Radio Button 值
- netlogo - 在 netlogo 中使用比例颜色
- javascript - Sinon - 间谍在对象上包装 *any* 属性访问
- r - 如何在 R 数据框中缩放列的段?
- node.js - NodeJS - 如何增加内存堆大小?
- android - Firebase 匿名身份验证在应用升级时丢失
- php - PHP 中的 For 循环,只有一个循环的唯一输出
- r - 为什么我的闪亮仪表板自定义 CSS 不起作用?