2

I am trying to analyse a dataframe using Pandas. My question is similar to the question:

How to get rows with min values in one column, grouped by other column, while keeping other columns?

In addition to that question (which is very important in my case), I also need to find the min value of the other columns if there are multiple min values for grouped column. If not, I need to see the corresponding values.

Here is a basic example;

df = pd.DataFrame({'id' : [1,1,1,2,2],
                   'A' : [8,6,6,8,9],
                   'B' : [1,2,4,5,4]})

When this dataframe is grouped by 'id' and aggregated (first on 'A', then on 'B') as I want, here is the output I want to see:

id  A   B   
1   6   2
2   8   5

Note that, there are multiple rows having min value for the column 'A' when id is 1. The corresponding 'B' column values are 2 and 4. Thus, the min of them is returned as the result for the 'B' column.

I do not know R, so, I did not understand the answer from the link above. Anyway, this is a different version of it.

2 Answers 2

3

IIUC, using idxmin after sorting by B


df.loc[df.sort_values('B').groupby('id')['A'].idxmin()]

   id  A  B
1   1  6  2
3   2  8  5
0
1

Another way is taking advantage of groupby sorts group_keys by default. So, groupby 'id, A' will push groups of min A per ID to the top. After that, call min on B, reset_index and drop_duplicate

df.groupby(['id', 'A'])['B'].min().reset_index().drop_duplicates(subset='id')


Out[298]:
   id  A  B
0   1  6  2
2   2  8  5

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.