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

2
  • 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 i and j are separate variables from the values which exist in the column modifying them alone will not modify the dataframe. Commented Aug 31, 2021 at 23:09
  • Also useful information here: Pandas conditional creation of a series/dataframe column Commented Aug 31, 2021 at 23:14

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.