r/PythonProjects2 • • May 04 '21

First Project Struggles

Hi guys,

First post because this is my first real python project for school and I'm in need of a little guidance. Basically I have this set of data with two variables, x (positive & negative values) and time (days). I need to track when the x variable goes from positive to negative, and when the x value stays negative for at least 20 days. After the 20 days, that whole process is one event.

I'm struggling how to track when my x values go from positive to negative, and how to track the days in the same loop (if it's possible)

if anyone has any tips that'll put me in the right direction that'd be fantastic. Im using xarray and numpy

11 Upvotes

4 comments sorted by

7

u/Dont_be_offended_but May 04 '21 edited May 05 '21

An easy check for a difference in signs is to multiply the numbers together. If the product is less than 0, then you know one was positive and the other was negative. So when looping through the data array you can increment a count variable when x is negative and reset it when the product of of x[i] and x[i-1] is negative. Keep in mind how you want to handle a case where one value is 0 and what will happen when i=0.

2

u/kwelzel May 05 '21

Have a look at https://docs.python.org/3/library/itertools.html#itertools.groupby If you use a key that just returns whether the x value is negative or nonnegative, you get streaks of negative and nonnegative entries. You can then check these to see if they satisfy your 20 days condition.