'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:

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


Solution 1:[1]

IIUC, you can use a named GroupBy and get last-first:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1