0

I have 2 columns in a dataframe, one named "day_test" and one named "Temp Column". Some of my values in Temp Column are negative, and I want them to be 1 or 2. I've made a for loop with 2 if statements:

for (i,j) in zip(df['day_test'].astype(int), df['Temp Column'].astype(int)):

if i == 2 and j < 0:
    j = 2


if i == 1 and j < 0:
    j = 1

I tried printing j so I know the loops are working properly, but the values that I want to change in the dataframe are staying negative.

Thanks

Tony
  • 31
  • 3
  • 1
    There seems to be a fundamental understanding of what `i` and `j` are in terms of your ability to modify them and have those changes affect the underlying column. Some general information here [Python: list is not mutated after for loop](https://stackoverflow.com/q/35874023/15497888) `i` and `j` are separate variables from the values which exist in the column modifying them alone will not modify the dataframe. – Henry Ecker Aug 31 '21 at 23:09
  • Also useful information here: [Pandas conditional creation of a series/dataframe column](https://stackoverflow.com/q/19913659/15497888) – Henry Ecker Aug 31 '21 at 23:14

1 Answers1

0

Your code doesn't change the values inside the dataframe, it only changes the j value temporarily. One way to do it is this:

df['day_test'] = df['day_test'].astype(int)
df['Temp Column'] = df['Temp Column'].astype(int)

df.loc[(df['day_test']==1) & (df['Temp Column']<0),'Temp Column'] = 1

df.loc[(df['day_test']==2) & (df['Temp Column']<0),'Temp Column'] = 2
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30