You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中获取鸡肉类别最高价格的对应行?

获取指定类别中价格最高的行

构造示例DataFrame

先还原你提供的数据集:

import pandas as pd

data = {
    'Meat type': ['beef', 'beef', 'chicken', 'chicken', 'pork', 'pork'],
    'brand': ['A', 'B', 'A', 'B', 'A', 'B'],
    'Price': [10, 12, 11, 14, 9, 16]
}
df = pd.DataFrame(data)

方法一:筛选子集后取最大行(最直观)

先过滤出Meat type为chicken的行,再用nlargest直接提取价格最高的1行:

chicken_max_row = df[df['Meat type'] == 'chicken'].nlargest(1, 'Price')

执行后得到的结果即为目标单行DataFrame:

Meat typebrandPrice
chickenB14

方法二:通过索引定位最大值行

先筛选出chicken的子集,再找到价格最大值对应的索引,最后提取该行:

# 筛选chicken数据
chicken_subset = df[df['Meat type'] == 'chicken']
# 获取Price最大值的索引
max_price_idx = chicken_subset['Price'].idxmax()
# 提取目标行(用loc保持DataFrame格式)
chicken_max_row = chicken_subset.loc[[max_price_idx]]

方法三:批量处理多类别场景(扩展用法)

如果后续需要获取每个肉类的最高价格行,再筛选chicken的结果,可以用groupby:

# 按Meat type分组,每组取Price最高的行
all_max_rows = df.groupby('Meat type', group_keys=False).apply(lambda x: x.nlargest(1, 'Price'))
# 筛选chicken的结果
chicken_max_row = all_max_rows[all_max_rows['Meat type'] == 'chicken']

内容的提问来源于stack exchange,提问作者Victor Zhong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 23:25:28