kshikama - 1 year ago 127
Python Question

How to make pandas/core/generic/pct_change to return a positive value when changing from a negative to a positive value

ipdb> df["input"]
datetime
2011-01-01    2.577163
2011-01-02    0.579833
2011-01-03   -0.191187
2011-01-04    0.430754

ipdb> df["input"].pct_change()
datetime
2011-01-01         NaN
2011-01-02   -0.775011
2011-01-03   -1.329728
2011-01-04   -3.253050


I want the value of
2011-01-04 -3.253050
to be 3.253050. Is there an option in pct_change() function that would allow this? Otherwise, what would be an efficient way to do this?

Essentially for each pct_change calculation, I want to multiply by -1 if the previous value < 0 and the current value is > 0. Ideally I want a way that doesn't use a for loop in python but that is all that comes to mind now.

You can write your condition out and multiply by -1 wherever it's met:

>>> p = df["input"].pct_change()
>>> p
datetime
2011-01-01         NaN
2011-01-02   -0.775011
2011-01-03   -1.329728
2011-01-04   -3.253051
Name: input, dtype: float64
>>> p.loc[(df["input"].shift() < 0) & (df["input"] > 0)] *= -1
>>> p
datetime
2011-01-01         NaN
2011-01-02   -0.775011
2011-01-03   -1.329728
2011-01-04    3.253051
Name: input, dtype: float64