if statement and for loop
I am stuck with the following code, I have a column in which I want to divide by 2 if the number is above 10 and run this for all the rows. I have tried this code but it gives the error of the series is ambiguous:
JavaScript
x
5
1
if df[x] > 10:
2
df[x]/2
3
else:
4
df[x]
5
I suppose that I need a for loop in combination with the if statement. However I could not make it running, anyone has some ideas?
Advertisement
Answer
The easiest approach, I think, is to use boolean indexing. For example:
JavaScript
1
7
1
df = pd.DataFrame( # create dataframe
2
20*np.random.rand(6, 4),
3
columns=list("ABCD"))
4
print(df) # print df
5
df[df>10]/=2 # divide entries over 10 by 2
6
print(df) # print df
7
Result:
JavaScript
1
16
16
1
A B C D
2
0 1.245686 1.443671 17.423559 17.617235
3
1 13.834285 10.482565 2.213459 9.581361
4
2 0.290626 14.082919 0.224327 11.033058
5
3 5.113568 5.305690 19.453723 3.260354
6
4 14.679005 8.761523 2.417432 4.843426
7
5 15.990754 12.421538 4.872804 5.577625
8
9
A B C D
10
0 1.245686 1.443671 8.711780 8.808617
11
1 6.917143 5.241283 2.213459 9.581361
12
2 0.290626 7.041459 0.224327 5.516529
13
3 5.113568 5.305690 9.726862 3.260354
14
4 7.339503 8.761523 2.417432 4.843426
15
5 7.995377 6.210769 4.872804 5.577625
16