如何获取包含特定标题最大值的列在pandas数据帧中?

huangapple go评论126阅读模式
英文:

How can I get a column that contains the maximum value of a specific header in panda dataframe?

问题

我想要获取肉类类型为"chicken"中价格最高的一行,应该怎么做?

英文:

Suppose I have a table like this:

Meat type brand Price
beef A 10
beef B 12
chicken A 11
chicken B 14
pork A 9
pork B 16

I want to get a column that has the greatest price from meat type chicken,like this:

Meat type brand Price
chicken B 14

what should I do?

答案1

得分: 1

你可以使用 idxmax() 函数。首先,筛选以选择类型为 chicken 的行,然后找到 'Price' 的最大值的索引:

df.loc[df[df['Meat type'] == 'chicken']['Price'].idxmax()]
英文:

You can use idxmax() function. First, filter to select rows where the type is chicken, then find the index of max 'Price':

df.loc[df[df['Meat type'] == 'chicken']['Price'].idxmax()]

答案2

得分: 1

使用筛选器选择仅包括"chicken"肉类的行,然后使用"max"函数找到具有最高价格的行。

import pandas as pd    

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

chicken_df = df[df['Meat type'] == 'chicken']    

max_row = chicken_df.loc[chicken_df['Price'].idxmax()]

print(max_row)

输出:

Meat type    chicken
brand              B
Price             14
Name: 3, dtype: object
英文:

Use a filter to select only the rows where the meat type is "chicken", and then use the "max" function to find the row with the highest price.

import pandas as pd    

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

chicken_df = df[df['Meat type'] == 'chicken']    

max_row = chicken_df.loc[chicken_df['Price'].idxmax()]

print(max_row)

Out:

Meat type    chicken
brand              B
Price             14
Name: 3, dtype: object

答案3

得分: 1

首先筛选出只有鸡肉的部分,然后按价格排序并取前1个。

df[df['Meat type'] == 'chicken'].sort_values(by='price', ascending=False).head(1)
英文:

Filter only chicken first. Then sort by price and take top 1.

df[df['Meat type'] == 'chicken'].sort_values(by='price', ascending=False).head(1)

答案4

得分: 0

df[df['Meat'].eq('chicken')].sort_values('Price').iloc[-1]

Explanation

eq就像==

我正在寻找MeatChicken的行,然后按Price值进行排序。

默认是升序排列。

所以我使用iloc[-1]获取最后一个。

英文:
df[df['Meat'].eq('chicken')].sort_values('Price').iloc[-1]

Explanation

eq is like ==

I am looking for the rows where Meat is Chicken, then sort Price values.

Default is ascending order.

So I get the last one with using of iloc[-1]

huangapple
  • 本文由 发表于 2023年3月12日 17:00:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定