Python – 按元組鍵聚合值


簡介

在當今世界,對於擁有大量資料的組織來說,資料處理是最具挑戰性的任務之一。隨著資料科學和機器學習的發展,資料訪問變得更加容易。Python 語言在處理這些資料方面發揮著至關重要的作用,因為存在的資料可能彼此相關或不相關。當它們具有一定的相關性時,可以將其與其他資料組合儲存,或者簡單地進行資料聚合。在這個過程中,它將具有相似特徵和屬性的元素組合在一起。為了完成此過程,需要使用一些內建函式和庫。

按元組鍵聚合值

元組是一種資料結構,它包含在初始化後可互換的元素。元組通常被賦值,並根據使用者的角度返回語句。

語法

reduce()

Python 中的 collections 模組包含許多子類,例如“defaultdict()”和 reduce() 方法。reduce() 方法始終使用兩個引數,然後將它們縮減為單個值。

方法

方法 1 - 使用 defaultdict() 方法

方法 2 - 使用 groupby() 方法

方法 1:使用 defaultdict() 方法聚合值的 Python 程式碼

Defaultdict 類用於使用 Python 語言 collections 庫下的字典方法聚合值。產品與其各自的過期日期和產品成本價一起列出。字典資料結構被定義為一個整數變數,它建立一個字典,其鍵為產品、日期字串的元組,然後將這些值與產品的成本追加到鍵元組中。

演算法

  • 步驟 1 - 輸入字串宣告為 Item_expiry,其中包含一組字串。

  • 步驟 2 - 按元組鍵聚合值所需的庫是 defaultdict。

  • 步驟 3 - for 迴圈用於遍歷元組的每個元素。

  • 步驟 4 - 透過追加專案名稱、每個專案的過期日期和每個專案的成本列印輸出。

示例

# initializing the Item_expiry in a list of values
Item_expiry = [
   ('Milk', 30),
   ('Tomato', 100),
   ('lentils', 345),
   ('Milk', 320)
]
#importing the defaultdict function from collections module
from collections import defaultdict
#creating the dictionary defaultdict of float data type and storing in sums_by_product_days
sums_by_product_days = defaultdict(float)
#Using for loop to iterate through different values of Item_expiry list and adding the cost value to the existing key sums_by_product_days
for product, cost in Item_expiry:
   sums_by_product_days[(product)] += cost
#Returns the values of newly created dictionary   
print(sums_by_product_days)

輸出

defaultdict(<class 'float'>, {'Milk': 350.0, 'Tomato': 100.0, 'lentils': 345.0})

方法 2:使用 groupby() 方法聚合值的 Python 程式碼

匯入 pandas 庫,並列出產品及其各自的過期日期和產品成本價。使用 groupby() 函式對產品和過期日期進行分組,鍵為使用 sum 方法新增的總和。最後,藉助 print 語句返回帶有欄位的產品。

演算法

  • 步驟 1 - 輸入字串宣告為 Item_expiry,其中包含一組字串。

  • 步驟 2 - 按元組鍵聚合值所需的庫是 pandas。

  • 步驟 3 - 透過追加專案名稱、每個專案的過期日期和每個專案的成本列印輸出。

示例

#importing the pandas module
import pandas as pd
# initializing the DataFrame in a list of values with product name, expiry date, and cost
df = pd.DataFrame({
   'product': ['Milk', 'Tomato', 'Lentils', 'Tomato'],
   'expiry': ['1 day', '3 day', '6 months', '3 day'],
   'cost': [30, 100, 345, 50]
})
# Using the groupby function to combine the above dataframes by product and expiry and adding the costs
sums_by_product_days = df.groupby(['product', 'expiry'])['cost'].sum()
#Returns the values as list of elements
print(sums_by_product_days)

輸出

product  expiry  
Lentils  6 months    345
Milk     1 day        30
Tomato   3 day       150
Name: cost, dtype: int64

結論

在 Python 語言中,使用括號“()”來指示您已聲明瞭一個元組。這些括號內的元素可以定義為初始化為元組的元素。元組的優點是它遵循定義元素的特定順序。

更新於: 2023年8月25日

229 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告