Pandas get group,如何根据词组中的关键词进行分组?

Pandas get group, how to get group by keywords out of a phrase?

假设我有以下内容:

Item Quantity
Blue Banana 3
Red Banana 4
Green Banana 1
Blue Apple 2
Orange Apple 6

我想抓起所有的香蕉并添加它们,无论颜色如何。 或者我想抓取所有蓝色物品,无论水果类型如何,然后添加它们。

您可以使用字典理解和 str.contains:

words = ['banana', 'blue']

pd.Series({w: df.loc[df['Item'].str.contains(w, case=False), 'Quantity'].sum()
            for w in words})

输出:

banana    8
blue      5