Reputation: 59
I'm stuck with the moment of appending new values to equation, so any help is welcome.
Assuming I have dataframe like this:
Name| A | B |
A | 30| 0 |
A | 15| 5 |
B | 10| 5 |
A | 94| 40|
B | 30| 40|
A | 15|125|
A | 3 |150|
and c=0.01
I want to reproduce the next rule: A1[A]-A2[B]*c+A2[A]+...+An
WHILE > 0
. So, since A1[A]-A2[B]*c+A2[A] > 0
at the next step the A3[A]
must be added to the initial equation and so on till the condition will be met
But I can't get how to append An to the end of the equation.
For now my code looks like this:
for a in df['Name']:
c = 0.1
shift = 1
sum = df[df['Name']=='A']['A'] - df[df['Name']=='A']['B'].shift(-1)*c + df[df['Name']=='A']['A'].shift(-shift)
while sum >0:
shift=+1
sum = sum+df[df['Name']=='A']['A'].shift(-shift)
The problem in the code that I have just computations for each pair of A-s and the output is
0 44.5
1 105.0
3 96.5
5 4.0
6 NaN
While I need the program to continue addition of the n-th A value to initial equation while the sum is >0
Upvotes: 3
Views: 110
Reputation: 30930
c = 0.1
A =df.loc[df['Name'].eq('A')].reset_index(drop=True)
Case 1: If the first value of A[B]
is 0 as in the example.
s = ( A['A'].sub(A['B'].mul(c))
.where(A.index <2,A['A'])
.cumsum() )
print(s)
0 30.0
1 44.5
2 138.5
3 153.5
4 156.5
dtype: float64
Case 2: first value of A[B] isn't 0
s = ( A['A'].sub(A['B'].mul(c).mask(A.index==0,0))
.where(A.index <2,A['A'])
.cumsum() )
s[s.le(0).cumsum().eq(0)].iloc[-1]
Output
156.5
Upvotes: 2
Reputation: 150785
IIUC, you can do:
# extract the name A
dfA = df[df.Name=='A']
# compute cumulative sum of A1[A] - A2[B]
s = dfA['A'].sub(dfA['B'].shift(-1).mul(-c).fillna(0)).cumsum()
# find the last positive value
# might need to check if there is one
s[s.le(0).cumsum().eq(0)].iloc[-1]
Output:
160.2
Upvotes: 1