首页 > 解决方案 > 使用 Pandas 订购的最贵商品的数量是多少

问题描述

我的 DF 在ascending=False下面

chipo_name_price_desc

        item_name   item_price
2624    Steak Salad Bowl    9.39
4419    Steak Salad Bowl    9.39
4036    Steak Salad Bowl    9.39
1825    Barbacoa Salad Bowl 9.31
3115    Carnitas Salad Bowl 9.19
5000    Meat Salad Bowl     9.39

订购的最贵商品的数量是多少? chipo_name_price_desc.loc[chipo_name_price_desc['item_name'] == 'Steak Salad Bowl'].count()

预期:牛排沙拉碗 3 肉沙拉碗 1

还有比这更好的方法吗?

标签: pandas

解决方案


使用Series.maxSeries.shape

在不使用的情况下,sort我们可以得到maxof item_price,然后使用 得到数量Series.shape

df[df['item_price'] == df['item_price'].max()].shape[0]

#Out
3

使用GroupBysort

或者,如果您使用排序,我们可以获取第一组GroupBy并检查大小:

grps = [grp for _, grp in df.groupby('item_name', sort=False)]
print(grps[0].shape[0])

#Out
3

不是很笼统,但是如果想在groupby之后得到某个组,GroupBy.get_group按索引名使用:

df.groupby('item_name').get_group('Steak Salad Bowl').shape[0]

#Out
3

推荐阅读