0

I'm doing a mock financial report. One of the requirements is to find the biggest increase and decrease in profits from 1 month to another as well as the month that this occurred. I've had no trouble finding the min and max changes in profits but have no clue on how to find the month that said changes occur.

here is the header of the data frame

    Date    Profit/Losses
0   Jan-2010    867884
1   Feb-2010    984655
2   Mar-2010    322013
3   Apr-2010    -69417
4   May-2010    310503

and my current code

diff = [df["Profit/Losses"][i]-df["Profit/Losses"][i-1] for i in range(1,len(df["Profit/Losses"]))]

max_change = max(diff)
min_change = min(diff)
tot_change = sum(diff)

what is the best approach to return the corresponding date value for the maximum and minimum values? For example: I am looking to return that Feb-2012 is the month with the greatest increase in profits.

1
  • You need to give some sample of the data and the expected result in order for us to help. There is not enough info to work with Commented Jan 10, 2020 at 0:13

2 Answers 2

3
import numpy as np

df = pd.DataFrame({'Profit/Losses': np.random.rand(100)*10000})

df['diff'] = df['Profit/Losses'].shift(1) - df['Profit/Losses']

df.iloc[np.argmax(df['diff'])]
df.iloc[np.argmin(df['diff'])]
Sign up to request clarification or add additional context in comments.

Comments

2

Use Series.diff

d = df['Profit/Losses'].diff()
#d = df['Profit/Losses'].diff(-1)
print(d)
0         NaN
1    116771.0
2   -662642.0
3   -391430.0
4    379920.0
Name: Profit/Losses, dtype: float64

max_change = df.loc[d.idxmax(),'Date']
min_change = df.loc[d.idxmin(),'Date']
tot_change = d.sum()
print(max_change)
#May-2010

print(min_change)
#Mar-2010

Comments

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.