TheLeveyBreaks
TheLeveyBreaks

Reputation: 1

How to do for loops with conditions in python data frame

I am currently trying to add 1 to an entire column if the value(int) is greater than 0. The code that I am currently using for it is like so:`

for coldcloudy in final.coldcloudy:
    final.loc[final['coldcloudy'] > 0,coldcloudy] +=1

However I keep on getting a 'KeyError: 0' with it. Essentially, I want the code to go row by row in a particular column and add 1 if the integer is zero. for the values that are added by 1, I will add to another column. Can someone please help?

Upvotes: 0

Views: 46

Answers (1)

Scott Boston
Scott Boston

Reputation: 153530

You don't need for loop:

final = pd.DataFrame({'coldcloudy':np.random.choice([0,1],20)})

final.loc[final.coldcloudy > 0, 'coldcloudy'] += 1

print(final)

Output:

    coldcloudy
0            2
1            2
2            0
3            0
4            2
5            2
6            0
7            2
8            0
9            0
10           2
11           2
12           0
13           2
14           2
15           0
16           2
17           0
18           2
19           2

Upvotes: 3

Related Questions