lundi 22 novembre 2021

Pandas While loop through rows until criteria is met

I have a dataframe that represents a scatter plot. The goal is to limit the change in slope between points to no more than 0.5 degrees.

def calc_slope(frame):
    frame['slope'] = (frame['y'].shift(1)) - frame['y'])  / (frame['x'].shift(1) - frame['x'])
    frame['slope-change'] = frame['slope'] - frame['slope'].shift(-1)
    frame['check-slope'] = ['FAIL' if abs(x) > 0.5 else 'OK' for x in frame['slope-change']]

data = [[1,10.1],[2,10],[3,9.5],[4,9.4],[5,9.3],[6,10],[7,8.5],[8,9.4],[9,10],[10,8]]
df = pd.DataFrame(data,columns=['x','y'])
calc_slope(df)

Now the problem I have is that the I need to increase the y values at point number 7 and 10 in increments of 0.1 until they pass the check, I believe I need a while loop to accomplish this. Here my current attempt which is not working.

while  df.loc[df['check-slope'] == "FAIL"]:
    if row['check-slope'] == "FAIL" and row['slope-change'] < 0:
        row['y'] += 0.1
    elif row['check-slope'] == "FAIL" and row['slope-change'] > 0:
        row[idx+1] += 0.1
    calc_slope(df)

Any help is appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire