Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I subtract values in a dataframe from the previous row sequentially?

Supposing I have a data frame that looks like:

col1 col2
0    10
1    23
2    21
3    15

I want to subtract each value in col2 with the previous row sequentially, so that we are subtracting the previously subtracted value to get:

col1 col2
0    10 # left unchanged as index == 0
1    13 # 23 - 10
2    8  # 21 - 13
3    7  # 15 - 8

Other solutions that I have found all subtract the previous values as is, and not the new subtracted value. I would like to avoid using for loops as I have a very large dataset.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try below to understand the ‘previously subtracted’

b2 = a2 - a1
b3 = a3 - b2 = a3 - a2 + a1
b4 = a4 - b3 = a4 - a3 + a2 - a1
b5 = a5 - b4 = a5 - a4 + a3 - a2 + a1

So we just do

s = np.arange(len(df))%2
s = s + s - 1
df['new'] = np.tril(np.multiply.outer(s,s)).dot(df.col2)
Out[47]: array([10, 13,  8,  7])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading