首页 > 解决方案 > 在 python 中过滤或分组数据的更好方法

问题描述

我对 python 完全陌生,并且努力知道如何以更好的方式过滤或分组我的数据。让我给出上下文。我正在使用Djangoandcursor进行复杂的查询。从查询中获得结果后,我想以我的方式对数据进行分组:

# 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             |
|-----|-------|---------|---------------|

我想要的结果是通过以下步骤:

  1. 创建新的空白列表(现在称为结果)
  2. 从第一行开始,检查state结果中是否已经存在的行。如果没有,检查item结果中是否存在。如果没有,则将该行推入结果。
  3. 如果列表中存在状态或行,则跳过该行
  4. 填充结果后,对结果列表进行排序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'])

我找到了一些不错的库,例如numpyorpandas但我发现它在这里可能没用。我在这里发布问题以了解这种逻辑的更好方法。

我会很感激一些帮助!

标签: python

解决方案


推荐阅读