如何在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 type | brand | Price |
|---|---|---|
| chicken | B | 14 |
方法二:通过索引定位最大值行
先筛选出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
相关产品推荐
相关产品推荐

