簡體   English   中英

Pandas Dataframe:groupby id查找最大列值並返回另一列的對應值

[英]Pandas Dataframe: groupby id to find max column value and return corresponding value of another column

我有一個帶有不同食物條目的大型 dataframe。 每種食物都有一種營養素(A、B、C、D),該營養素在另一列中具有相應的值。 我想定義一個 function ,它將特定營養素作為參數並返回具有最高營養素值的食物的名稱 如果參數不存在,它應該返回“抱歉,{requested nutrient} not found”。

df = pd.DataFrame([[0.99, 0.87, 0.58, 0.66, 0.62, 0.81, 0.63, 0.71, 0.77, 0.73, 0.69, 0.61, 0.92, 0.49],
               list('DAABBBBABCBDDD'),
               ['apple', 'banana', 'kiwi', 'lemon', 'grape', 'cheese', 'eggs', 'spam', 'fish', 'bread',
                'salad', 'milk', 'soda', 'juice'],
               ['***', '**', '****', '*', '***', '*', '**', '***', '*', '*', '****', '**', '**', '****']]).T
df.columns = ['value', 'nutrient', 'food', 'price']

我嘗試了以下方法:

def food_for_nutrient(lookup_nutrient, dataframe=df):
    max_values = dataframe.groupby(['nutrient'])['value'].max()
    result = max_values[lookup_nutrient]
    return print(result)

它似乎正確識別了營養素的最大值,但它只返回營養素值。 我需要來自列food的相應 str 。 例如,如果我給出以下論點

food_for_nutrient('A‘)

我想要的 output 是:

banana

我的第二個問題是我的if 語句不起作用。 它總是返回else

def food_for_nutrient(lookup_nutrient, dataframe=df):
    max_values = dataframe.groupby(['nutrient'])['value'].max()
    if lookup_nutrient in dataframe['nutrient']:
        result = max_values[lookup_nutrient]
        return print(result)
    else:
        return print(f'Sorry, {lookup_nutrient} not found.')

food_for_nutrient('A')

非常感謝你的幫助!

嘗試這個:

def food_for_nutrient(lookup_nutrient):
    try:
        return df[df['nutrient'] == lookup_nutrient].set_index('food')['value'].astype(float).idxmax()
    except ValueError:
        return f'Sorry, {lookup_nutrient} not found.'

Output:

>>> food_for_nutrient('A')
'banana'

>>> food_for_nutrient('B')
'cheese'

>>> food_for_nutrient('C')
'bread'

>>> food_for_nutrient('D')
'apple'

>>> food_for_nutrient('E')
'Sorry, E not found.'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM