Python – 按元组键聚合值
介绍
在当前世界中,处理数据是组织面临的最具挑战性的任务,随着数据科学和机器学习的发展,访问数据变得更加容易。而Python语言在处理这些数据方面扮演着重要的角色,因为数据之间可能存在相关或无关。当它们之间有一定的相关性时,可以将它们与其他数据结合存储,或者仅仅是对数据进行聚合。在这种情况下,它将具有相似特征和属性的元素组合在一起。为了进行这个过程,需要使用一些内置函数和库。
按元组键聚合值
元组是一个由初始化后可互换的元素组成的数据结构。元组通常被赋予一个值,并根据用户的视角返回相应的语句。
语法
reduce()
Python中的collection模块有许多子类,如”defaultdict()”和reduce()方法。reduce()方法总是使用两个参数,然后将它们减少为一个值。
方法
方法1 – 使用defaultdict()方法
方法2 – 使用group()方法
方法1:使用defaultdict()方法聚合值的Python代码
默认字典类用于使用Python语言的collection库中的字典方法对值进行聚合。产品及其相应的到期日期和产品成本价位列出。字典数据结构被定义为整数变量,并且它创建一个字典,其键为产品、day_str的元组,然后这些值被附加到产品的成本。
算法
- 第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})
Python代码实现集合函数groupby()的方式二
导入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语言中,用方括号「()」来标示声明一个元组。这些方括号内的元素可以定义为元组的初始化元素。元组的优点是它遵循元素定义的特定顺序。