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 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.