使用 Python 對相似索引元素進行分組記錄


在 Python 中,可以使用 pandas 和 numpy 等庫對相似索引元素進行記錄分組,這些庫提供了多個用於執行分組的功能。根據相似索引元素對記錄進行分組用於資料分析和操作。在本文中,我們將瞭解和實現各種方法來對相似索引元素進行記錄分組。

方法 1:使用 pandas groupby()

Pandas 是一個功能強大的資料操作和分析庫。groupby() 函式允許我們根據一個或多個索引元素對記錄進行分組。讓我們考慮一個數據集,其中我們有一個學生成績的資料集,如下例所示。

語法

grouped = df.groupby(key)

這裡,Pandas GroupBy 方法用於根據一個或多個鍵對 DataFrame 中的資料進行分組。“key”引數表示應根據其對資料進行分組的列或列。生成的“grouped”物件可用於分別對每個組執行操作和計算。

示例

在下面的示例中,我們使用 groupby() 函式根據“Name”列對記錄進行了分組。然後,我們使用 mean() 函式計算每個學生的平均分數。生成的 DataFrame 顯示每個學生的平均分數。

import pandas as pd

# Creating a sample DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob'],
    'Subject': ['Math', 'English', 'Math', 'English', 'Math'],
    'Score': [85, 90, 75, 92, 80]
}

df = pd.DataFrame(data)

# group by name
grouped = df.groupby('Name')

# calculate mean value of grouped data
mean_scores = grouped.mean()
print(mean_scores)

輸出

Name       Score   
Alice      88.5
Bob        85.0
Charlie    75.0

方法 2:使用 collections 模組中的 defaultdict

Python 中的 collections 模組提供了一個 defaultdict 類,它是內建 dict 類的子類。它透過在鍵不存在時自動建立新的鍵值對來簡化分組過程。

語法

groups = defaultdict(list)
groups[item].append(item)

這裡,語法使用 collections 模組中的 defaultdict() 函式初始化一個名為 groups 的 defaultdict 物件,其預設值為一個空列表。第二行程式碼使用鍵(item)訪問與 groups 字典中該鍵關聯的列表,並將該項附加到列表中。

示例

在下面的示例中,我們使用了一個 defaultdict,其預設值為列表。我們遍歷 scores 列表並將科目分數對附加到 defaultdict 中相應學生的鍵。生成的字典顯示分組後的記錄,其中每個學生都有一個科目分數對的列表。

from collections import defaultdict

# Creating a sample list of scores
scores = [
    ('Alice', 'Math', 85),
    ('Bob', 'English', 90),
    ('Charlie', 'Math', 75),
    ('Alice', 'English', 92),
    ('Bob', 'Math', 80)
]

grouped_scores = defaultdict(list)

for name, subject, score in scores:
    grouped_scores[name].append((subject, score))

print(dict(grouped_scores))

輸出

{'Alice': [('Math', 85), ('English', 92)],
 'Bob': [('English', 90), ('Math', 80)],
 'Charlie': [('Math', 75)]}

方法 3:使用 itertools.groupby()

Python 中的 itertools 模組提供了一個 groupby() 函式,該函式根據鍵函式對來自可迭代物件的元素進行分組。

語法

list_name.append(element)

這裡,append() 函式是列表方法,用於將元素新增到列表名稱的末尾。它透過將指定元素作為新項新增到列表中來修改原始列表。

示例

在下面的示例中,我們使用了 itertools 模組中的 groupby() 函式。在應用 groupby() 函式之前,我們使用 lambda 函式根據日期對 events 列表進行了排序。groupby() 函式根據日期對事件進行分組,我們遍歷這些組以提取事件名稱並將其附加到 defaultdict 中相應日期的鍵。生成的字典顯示分組後的記錄,其中每個日期都有一個事件列表。

from itertools import groupby

# Creating a sample list of dates and events
events = [
    ('2023-06-18', 'Meeting'),
    ('2023-06-18', 'Lunch'),
    ('2023-06-19', 'Conference'),
    ('2023-06-19', 'Dinner'),
    ('2023-06-20', 'Presentation')
]

events.sort(key=lambda x: x[0])  # Sort the events based on dates

grouped_events = defaultdict(list)

for date, group in groupby(events, key=lambda x: x[0]):
    for _, event in group:
        grouped_events[date].append(event)

print(dict(grouped_events))

輸出

{
'2023-06-18': ['Meeting', 'Lunch'],
 '2023-06-19': ['Conference', 'Dinner'],
 '2023-06-20': ['Presentation']
}

結論

在本文中,我們討論瞭如何使用不同的 Python 方法和庫根據相似索引元素對記錄進行分組。Python 提供了幾種方法來實現這一點,包括 pandas groupby() 函式、collections 模組中的 defaultdict 以及 itertools 模組中的 groupby() 函式。每種方法都有其優點,可以根據手頭任務的具體要求進行選擇。

更新於: 2023年7月17日

75 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.