vendredi 24 avril 2020

SettingWithCopyWarning: conditionally updating [i] with [i-1]+1 python

I have a dataframe with 2 columns (and approx 6000 rows) as shown:

head_ma  rec_time
NaN      1.0
8.20     1.0
8.21     1.0
8.22     1.0
8.23     1.0
8.21     1.0
8.20     1.0
8.19     1.0
8.20     1.0
...      ...

And I'm trying to loop through each [i] in the head_ma column in my dataframe and where [i] < [(i-1)], I want to update [i] in the rec_time column with [i-1]+1. The code I currently have works, but I get the error: "SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame"

How can I update my current code to avoid this please?

Current code:

for i in range (2, len(df)):
        if df.head_ma[i] < df.head_ma[(i-1)]:
            df.rec_time[i] = (df.rec_time[i-1]+1)

Aucun commentaire:

Enregistrer un commentaire