Krush23
Krush23

Reputation: 741

Sorting the columns based on value of a column. Pandas

df1

ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        A           30000
23661      BIKE          BLUE        B           43563
23661      BIKE          BLUE        C           45124
23661      BIKE          BLUE        D           28000
48684      CAR           RED         B           45145
48684      CAR           RED         D           35613
48684      CAR           RED         A           82312
48684      CAR           RED         C           24536
48684      CAR           RED         E           45613
54519      BIKE          BLACK       A           21345
54519      BIKE          BLACK       B           62623
54519      BIKE          BLACK       C           14613
54519      BIKE          BLACK       E           14365
54519      BIKE          BLACK       D           67353

Expecting outcome is the location that has the highest price for the vehicle.

ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        C           45124
48684      CAR           RED         A           82312
54519      BIKE          BLACK       D           67353

df.sort_values(df['PRICE'], ascending=False, kind='quicksort') Using this code we can manually do one by one. How to do this for the whole df.

Upvotes: 2

Views: 41

Answers (2)

Anchal Gupta
Anchal Gupta

Reputation: 337

U can do groupby on color column & then apply sort function on price: Something like this df.groupby(["COLOR"]).apply(lambda x: x.sort_values(["PRICE"], ascending = False))

Upvotes: 0

anky
anky

Reputation: 75080

sort_values + drop_duplicates:

df.sort_values(['ITEM','PRICE'],ascending=[True,False]).drop_duplicates('ITEM')

     ITEM CATEGORY  COLOR LOCATION  PRICE
2   23661     BIKE   BLUE        C  45124
6   48684      CAR    RED        A  82312
13  54519     BIKE  BLACK        D  67353

Upvotes: 2

Related Questions