Using Groupby

Asked 2 years ago, Updated 2 years ago, 46 views

I'd like to use Groupby to get the value of another variable when one variable is at its maximum. How should I describe it?
For example, http://ailaby.com/groupby_easy/
"I would like to get the price data (150,000 and 70,000) when the discount is the maximum in the ""Apply max"" section of , but could you tell me what kind of function it is?"

python pandas

2022-09-30 20:17

1 Answers

This is an example of a for statement with the CUSTOMER column as the key.
This is not very smart, so you might want to index the original DataFrame.

 from pandas import DataFrame

df = DataFrame(
    [['AA', 'TV', 150000, 20,000], ['BB', 'Camera', 70,000, 10000],
     ['AA', 'Video', 2000, 200], ['AA', 'Video', 3000, 150],
     ['BB', 'TV', 200000, 8000], ['BB', 'Camera', 50000, 5000],
     ['AA', 'Video', 1000, 200]],
    columns=['CUSTOMER', 'PRODUCT', 'PRICE', 'DISCOUNT'])

grouped = df.groupby('CUSTOMER')
discount_max = grouped ['DISCOUNT'].max()

for customer index_max.index:
    print(df.loc[(df['CUSTOMER']==customer)& 
                 (df['DISCOUNT'] == discount_max[customer]),
                 'PRICE'].values[0])


2022-09-30 20:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.