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
CodePudding user response:
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
CodePudding user response:
For subtract last value with first use aggregation GroupBy.last
with GroupBy.first
and substract:
df1 = df.groupby('month')['value'].agg(['first','last'])
out = df1['last'].sub(df1['first'])