Home > Enterprise >  Finding the index of a row based on values of the neightbouring rows
Finding the index of a row based on values of the neightbouring rows

Time:09-23

I am trying to automate a code for finding the location in which my timeseries has the first y-axis value closest to 0 with an upward trend, that is, the value before my y = 0 is very likely negative and the following one is positive where the exact location that I want to pin point is the closest to 0.

To illustrate what I mean. Let's say I have the given bellow:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

start_time = 0
end_time = 1
sample_rate = 500
time = np.arange(start_time, end_time, 1/sample_rate)
theta = 32
frequency = 2
amplitude = 1
sinewave = amplitude * np.sin(2 * np.pi * frequency * time   theta)

# DataFrame
df = pd.DataFrame([time, sinewave]).T
df.columns = ['Time','Signal']

plt.plot(df['Time'],df['Signal'])

For my specific example, the solution would be:

Index: 227, Time: 0.454, Signal: 0.00602037947

There are very likely several solutions for that problem. However, I do believe that there is probably a single-line elegant solution with Pandas that could handle the issue.

CodePudding user response:

here is one way do it

check the two consecutive rows where the sign changes for the signal

df[(df['Signal']>0) & 
   (df['Signal'].shift(1)<0)]
         Time   Signal
227     0.454   0.00602
477     0.954   0.00602

OR following to get the first instance

df[(df['Signal']>0) & 
   (df['Signal'].shift(1)<0)].iloc[0]
Time      0.45400
Signal    0.00602
Name: 227, dtype: float64
  • Related