开始使用免费开始使用

定义聚合函数

零售商对于库存中招牌类商品占比偏高感到惊讶,因此决定按不同类别做进一步聚合,以更好地探索数据。对您来说这并不难,但该零售商此前连最基本的交易与商品的描述性分析都无法完成。

零售商请您对 candlesbagsboxes 这几类进行聚合。为简化任务,您决定编写一个函数。函数接受一个字符串,表示某个商品的类别;然后输出一个 DataFrame,指示每笔交易是否包含该类别的商品。注意,pandas 已经以 pd 导入;此外,数据已按独热编码形式导入为 onehot

本练习是课程的一部分

Python 中的购物篮分析

查看课程

练习说明

  • 完成列表推导,从列名中提取所需的子集。
  • 选取您希望聚合的商品对应的列。
  • 使用函数 aggregate(),分别以字符串 bagboxcandle 对 bags、boxes 与 candles 执行聚合。

交互式实操练习

通过完成这段示例代码来试试这个练习。

def aggregate(item):
	# Select the column headers for sign items in onehot
	item_headers = [i for i in ____.columns if i.lower().find(item)>=0]

	# Select columns of sign items
	item_columns = onehot[____]

	# Return category of aggregated items
	return item_columns.sum(axis = 1) >= 1.0

# Aggregate items for the bags, boxes, and candles categories  
bags = aggregate('bag')
boxes = aggregate('____')
candles = ____
编辑并运行代码