pandas - 使用 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
还有比这更好的方法吗?
解决方案
使用Series.max
和Series.shape
在不使用的情况下,sort
我们可以得到max
of item_price
,然后使用 得到数量Series.shape
:
df[df['item_price'] == df['item_price'].max()].shape[0]
#Out
3
使用GroupBy
后sort
或者,如果您使用排序,我们可以获取第一组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
推荐阅读
- javascript - ReactJs 在 typescript-cra 模板中编译模块 react-particle-js 时出错
- javascript - JavaScript + Discord.js:另一个对象内的对象返回TypeError:无法读取未定义的属性
- pytorch - 如何使用 pytorch 的 grid_sample()?
- java - 如何在另一个具有更高spring版本的spring项目中使用将spring作为打包依赖项的jar?
- java - 如何重命名由 Lombok 管理的字段
- c++ - 在 C++ 中没有比较器函数的情况下,按对中的第一个元素按递增顺序对对向量进行 stable_sort
- android-studio - 如何在 Android Studio 的 android 模拟器上启用麦克风?
- r - 如何使用 ggplot 和 geom_bar() 在 r 中的条形图上添加 y 轴值?
- python - 如何为 Docker 设置动态值
- angular - 如何修复 Angular 9 应用程序中的 CDK 虚拟滚动。[PokeDex 应用程序]