1

I have following df

     A   B
0    1   10
1    2   20
2    NaN 5
3    3   1
4    NaN 2
5    NaN 3
6    1   10
7    2   50
8    Nan 80
9    3   5

Consisting of repeating sequences from 1-3 seperated by a variable number of NaN's.I want to groupby each this sequences from 1-3 and get the minimum value of column B within these sequences.

Desired Output something like:

     B_min
0    1
6    5

Many thanks beforehand

draj

1
  • post you written code Commented Mar 11, 2020 at 13:28

2 Answers 2

1

Idea is first remove rows by missing values by DataFrame.dropna, then use GroupBy.cummin by helper Series created by compare A for equal by Series.eq and Series.cumsum, last data cleaning to one column DataFrame:

df = (df.dropna(subset=['A'])
       .groupby(df['A'].eq(1).cumsum())['B']
       .min()
       .reset_index(drop=True)
       .to_frame(name='B_min'))
print (df)
   B_min
0      1
1      5
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I also was playing around with dropna first but I lack knowledge of such helper funcs like .eq(). Thank you very much!
1

All you need to df.groupby() and apply min(). Is this what you are expecting?

df.groupby('A')['B'].min()

Output:

A
1      10
2      20
3       1
Nan    80

If you don't want the NaNs in your group you can drop them using df.dropna()

df.dropna().groupby('A')['B'].min()

1 Comment

Unfortunately not, it’s not the desired output. Thanks anyways!

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.