Home > Software engineering >  Python pandas adding a column of one and two when changing the sign taking into account the same sig
Python pandas adding a column of one and two when changing the sign taking into account the same sig

Time:08-22

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 !

Can you tell me how to do it better ?

CodePudding user response:

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.

  • Related