Home > Software engineering >  Dataframe value changes based on a condition doesn't work even though printing it does
Dataframe value changes based on a condition doesn't work even though printing it does

Time:07-08

I have a DataFrame with Date, Time, Flow. I can print selections of it and it grabs the corresponding data correctly, but when I try to change the values, it does nothing.

The print statement below selects the corresponding data correctly.

df["Flow"][ df["Date"] == "2022-02-23" ] 

The reassignment below does nothing.

df["Flow"][ df["Date"] == "2022-02-23" ] = 100 

But if I take the selection out as seen below, it correctly changes the value.

df["Flow"] = 100

I'd like to add more conditions, but in all combinations of the other conditions, the print always works and the reassignment doesn't. Is there something basic I'm missing?

CodePudding user response:

Try something like this and see if it works:

df.loc[df["Date"] == "2022-02-23", "Flow"] = 100

CodePudding user response:

You could use a list comprehension: df["Flow"] = [100 if date == "2022-02-23" else df["Flow"][i] for i, date in enumerate(df["Date"])]

  • Related