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

Python pandas adding a column of one and two when changing the sign taking into account the same sign

I have a csv file that looks something like this:

Ema1 Ema2 Delta_ema Comulative
5 6 -1 -1
9 15 -6 -7
29 3 26 19
8 2 6 22
5 20 -15 7
2 21 -19 -12
8 22 -14 -26
30 2 28 2
6 5 1 3

I would like to add to this csv a column with the value of one when changing the sign in the Cumulative column, taking into account the same sign, so that it would turn out something like this csv

Ema1 Ema2 Delta_ema Comulative Answer
5 6 -1 -1 0
9 15 -6 -7 0
29 3 26 19 1
8 2 6 22 0
5 20 -15 7 0
2 21 -19 -12 -1
8 22 -14 -26 0
30 2 28 2 1
6 5 1 3 0

In my original csv file, the Comulative column usually does not change the sign from about 100 to 500 lines here , for clarity , it changes so often !

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

Can you tell me how to do it better ?

>Solution :

You can add a new column like this:

df['answer'] = np.diff(np.sign(df.Comulative), prepend=df.Comulative.to_numpy()[0]) // 2

and then save back to csv.

diff return the difference between two elements (rows). For the first element, the difference in NaN, so we prepend the first element to automatically get a differenc of 0.

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