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

Find the range from pandas column for each month

I have an pandas dataframe as

datetime   value month
2021-03-01  10   March
2021-03-28  15   March
2021-04-02  10   April
2021-04-05  12   April
2021-04-31  20   April
2021-05-10  15   May
2021-05-27  30   May

I would like to obtain the Last value from a Month – The first value of the month

The expected result should look like this:

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

Month  Value
March  15-10=5
April  20-10=10
May    30-15=15

>Solution :

IIUC, you can use a named GroupBy and get lastfirst:

g = df.groupby('month')['value']
out = g.last()-g.first()

or, using apply:

out = df.groupby('month')['value'].apply(lambda g: g.last()-g.first())

output:

month
April    10
March     5
May      15
Name: value, dtype: int64
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