Find the range from pandas column for each month

Data_User

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
mozway

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324293322&siteId=291194637