user1913171
user1913171

Reputation: 283

How to find index of previous data that is higher than current value with pandas?

I'm looking for more simple and fast way to find difference between 2 time series values using pandas.

I have the following time series data:

a = [100, 20, 0, 10, 10, 50]

I'd like to know the way to get index of value that is the higher than the current value.

For example, a[3] is 10.

And we move one step backward in order to search for higher value than 10.

a[2] is 0, which is lower than 10( == a[3]). So let's move to a[1].

a[1] is 20, which is higher than 10.

So the answer what I want is 2, which is (index of a[3] - index of a[1]).

In case of a[5] ( == 50), the answer what I want is 5, which is (index of a[5] - index of a[0]).

All the results would be the following:

func(a[0]) = 0

func(a[1]) = 0

func(a[2]) = 0

func(a[3]) = 2

func(a[4]) = 3

func(a[5]) = 5

It would be very helpful if you suggest any hints about implementing this kind of function.

Upvotes: 0

Views: 297

Answers (1)

sulkeh
sulkeh

Reputation: 947

I believe your listed output is not consistent with what you ask. This function may be what you want.

def func(l, index):
   for i in range( index):
      if l[index - i - 1] > l[index]:
         break
   else:
       return 0 # return 0 if it never finds a larger number (loop completes)

   return i + 1 # this should be the distance

It searches backwards, and returns the distance to the next number which is larger (and zero if none exist)

[func(a, i) for i in range(len(a))] gives

[0, 1, 1, 2, 3, 5]

Upvotes: 1

Related Questions