Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas 'min' aggregate, but how to set 'min'+1?

I’m trying to aggregate my pandas dataframe with minimum and also minimum+1. Let me explain.
Suppose I have a dataframe:

  distance  vertex  type
0   8       104     A
1   1       114     A
2   1       103     B
3   2       102     A
4   3       18      A
5   3       108     B

I get the minimum distance with groupby on Type as follows:

mask = df['distance'].isin(df.groupby(['type'])['distance'].agg('min').values)
df[mask]

This gives me minimum distance for each Type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  distance  vertex  type
1   1       114     A
2   1       103     B

My question: How do I get rows that are satisfying the following formula:

distance = minimum(distance) + 1

This is what I’m trying to get.

  distance  vertex  type
1   1       114     A
2   1       103     B
3   2       102     A

>Solution :

The exact logic is unclear, but assuming you want to filter per group to keep the values equal to the minimum or minimum +1, use groupby.transform:

mask = df['distance'].le(df.groupby(['type'])['distance'].transform('min').add(1))

out = df[mask]

Output:

   distance  vertex type
1         1     114    A
2         1     103    B
3         2     102    A
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading