4

I have a dataframe which has multi-level indexing. Here is a snippet of it:

import pandas as pd

data = {'EVENT_ID': [112335580,112335580,112335580,112335580,112335580,112335580,112335580,112335580, 112335582,
                     112335582,112335582,112335582,112335582,112335582,112335582,112335582,112335582,112335582,
                     112335582,112335582,112335582],

 'SELECTION_ID': [6356576,2554439,2503211,6297034,4233251,2522967,5284417,7660920,8112876,7546023,8175276,8145908,
                  8175274,7300754,8065540,8175275,8106158,8086265,2291406,8065533,8125015],

 'BSP': [5.080818565,6.651493872,6.374683435,24.69510797,7.776082305,11.73219964,270.0383021,4,8.294425408,335.3223613,
         14.06040142,2.423340019,126.7205863,70.53780982,21.3328554,225.2711962,92.25113066,193.0151362,3.775394142,
         95.3786641,17.86333041],

  'WIN_LOSE':[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]}

df = pd.DataFrame(data, columns=['EVENT_ID', 'SELECTION_ID', 'BSP','WIN_LOSE'])
df

df.set_index(['EVENT_ID', 'SELECTION_ID'], inplace=True)
df.sortlevel(level=0, ascending=True, sort_remaining=True)

I want to sort the BSP column for each EVENT_ID index separately.

I have tried the following:

data.assign(BSP=data.groupby(level=0).rank(ascending=False))

This does not work as it messes up the indexing and doesn't seem to sort the column anyway.

I have also tried just sorting in terms of the column but this also clearly just messes up the indexing.

1 Answer 1

4

This sorts by BSP ascending for each event ID:

df = pd.DataFrame(data, columns=['EVENT_ID', 'SELECTION_ID', 'BSP','WIN_LOSE'])
df = df.sort_values(["EVENT_ID","BSP"])
df.set_index(['EVENT_ID', 'SELECTION_ID'], inplace=True)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.