i Have a cross subtraction problem and i will like to have the solution for the same i have a data frame as shown below
input Y = 2
|X | A | Z |
|20 | 0 |18 |
|30 | 0 |-12 |
|40 | 0 |-52 |
|50 | 0 |-102|
:
:
:
The formulae for this is Y is given as a input by the user, where
z(row1) = x(row1) - Y
z(row2) = z(row1) - x(row2)
z(row3) = z(row2) - x(row3)
:
:
so on......
is there a way to code this using python using loops?
CodePudding user response:
You are effectively doing a cumulative sum with negative values and an offset of y
(except for the first row)
y = 2
df.loc[:, 'Z'] = -df['X'].cumsum() [40]*df.index.size - [y]*df.index.size
The addition of 40
is to undo the negation in the first row, or in other words
df.loc[:, 'Z'] = -df['X'].cumsum() [2*df.loc[0]['X']]*df.index.size - [y]*df.index.size
print(df)
# X Z
#0 20 18
#1 30 -12
#2 40 -52
#3 50 -102
CodePudding user response:
Since you're only working with the input once I would not put the first equation into the loop. If you want to store the data of x you have to add this as well
x = 20
z[0] = x - y
for i in range(9): # where 9 is number of rows you want to add
x = 10
z[i 1] = z[i] - x