我在尝试创建一起购买的商品的查找表时有点困难。
我有一个“强力”Python 迭代 DataFrame 的解决方案,但如果可能的话,我更喜欢使用某种聚合技巧的纯 Pandas 解决方案。
这是我所拥有的。我做了一个小例子,其中包含发票号码和购买的商品的列表。
import pandas as pd
df = pd.DataFrame({
"Invoice": [1, 1, 2, 3, 4, 4, 4, 5, 5],
"Item": ["Apple", "Pear", "Banana", "Apple", "Apple", "Orange", "Pear", "Apple", "Orange"]
})
df
我们可以看到 4 号发票有三项,而 2 号发票只有一项。
这是我不太满意的解决方案:
item_keys = []
item_values = []
for i, row in df.iterrows():
invoice = row["Invoice"]
item = row["Item"]
for item_2 in df[df["Invoice"] == invoice]["Item"]:
if item_2 != item:
item_keys.append(item)
item_values.append(item_2)
lookup_table = pd.DataFrame({"key": item_keys, "value": item_values})
lookup_table
在lookup_table中,我可以搜索关键商品并获取与其一起出售的所有商品。
有没有更快更优雅的方法来做到这一点?)
groupby
和 itertools.combinations
:
from itertools import combinations
lst = [c for _, g in df.groupby('Invoice')['Item']
for c in combinations(g, 2)]
out = pd.concat([pd.DataFrame(lst, columns=['key', 'value']),
pd.DataFrame(lst, columns=['value', 'key'])],
ignore_index=True)
输出:
key value
0 Apple Pear
1 Apple Orange
2 Apple Pear
3 Orange Pear
4 Apple Orange
5 Pear Apple
6 Orange Apple
7 Pear Apple
8 Pear Orange
9 Orange Apple