The best way to filter DataFrame by column A, condition on column B and give out min values of column C

Viewed 41

I am a newbie to python and pandas.

I want to get the Y values of every peak with the smallest gap

Here is my code so far which is very long and quite silly

for i in df.peaks.unique():
    min_y= df[df['peaks'] == i][df['gap'] == min(df[df['peaks'] == i]['gap'])]['y'].tolist()[0]
    print(min_y)

It works and this is the result:

171
204
246
278
311
416

Since, I saw some advanced syntax where people use apply, map, so they do not need to loop, can my task apply those techni ? Btw, I want to improve my code, please help!

The DataFrame is below for your informatin.

      x    y   w   h  peaks   gap
0    79  171  13  14  178.0   7.0
1   155  171  14  14  178.0   7.0
2   213  170  14  15  178.0   8.0
3   281  171  14  14  178.0   7.0
4   337  171  14  14  178.0   7.0
5    78  203  14  14  211.0   8.0
6   209  204  14  14  211.0   7.0
7   287  204  15  14  211.0   7.0
8   365  204  14  13  211.0   7.0
9    78  236  14  14  251.0  15.0
10  156  246  14  13  251.0   5.0
11  232  246  14  14  251.0   5.0
12   79  277  14  14  284.0   7.0
13  166  278  14  14  284.0   6.0
14  243  278  13  14  284.0   6.0
15   79  303  14  14  316.0  13.0
16  144  310  15  13  316.0   6.0
17  216  310  13  14  316.0   6.0
18  292  311  14  13  316.0   5.0
19  370  311  14  14  316.0   5.0
20   80  405  14  14  420.0  15.0
21  157  414  13  14  420.0   6.0
22  226  414  14  14  420.0   6.0
23  303  416  14  13  420.0   4.0
24  374  416  14  14  420.0   4.0
1 Answers

You can use groupby and combine it with idxmin

data.loc[data.groupby('peaks')['gap'].idxmin(), 'y']

# 0     171
# 6     204
# 10    246
# 13    278
# 18    311
# 23    416
# Name: y, dtype: int64
Related