Finding the first row which stratifies two conditions in python data frame

Viewed 45

I have a data frame which looks like this:

data frame

I want to write a code which locates points that have distance less than 250 from the next point. When it finds the point searches for the first point that is more than 250 away with speed greater than 5. For example in the sample data set, first find row 7 and then locate row 10 which is more than 250 away and has speed of 10.8 and return the index of row 10 I have write this code so far:

for i in (number+1 for number in range(data_gpd.index[-1]-1)):
if (data_gpd['distance'][i+1]< 250):

I'm not sure what should I do after this condition. I had in mind to use "Next" statement with conditions but I was only able to find it for list comprehension with one condition.

I really appreciate your help as I'm new to python and not sure which syntax would work better

1 Answers

You can use the pandas function loc and associated conditions to return a pandas DataFrame.

First Condition:

df['distance'] < 250

Second Condition:

df['speed'] > 5

Combined Condition:

(df['distance'] < 250) & (df['speed'] > 5)

Using loc and combined condition:

df.loc[(df['distance'] < 250) & (df['speed'] > 5)]

Input:

   time  location  distance   speed
0   300      9071      9071  108.00
1   300     18376      9304   11.00
2   300     28006      9630  115.00
3   200     30506      2500   45.00
4   400     31606      1100    9.90
5   500     31706       100    0.72
6   150     31756        50    1.20
7    20     31766        10    1.80
8    50     31916       150   10.80

Output:

   time  location  distance  speed
8    50     31916       150   10.8
Related