简体   繁体   English

python for循环与if语句来划分数字

[英]python for loop with if statement to divide numbers

if statement and for loop if 语句和 for 循环

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.我坚持使用以下代码,如果数字大于 10,我想在其中除以 2 并为所有行运行此列。 I have tried this code but it gives the error of the series is ambiguous:我已经尝试过这段代码,但它给出了该系列的错误是模棱两可的:

if df[x] > 10:
   df[x]/2
else:
   df[x]

I suppose that I need a for loop in combination with the if statement.我想我需要一个结合 if 语句的 for 循环。 However I could not make it running, anyone has some ideas?但是我无法让它运行,有人有什么想法吗?

It's not clear exactly what you're asking, but assuming you want to divide the element at x if it is > 10, you can simply do目前尚不清楚你在问什么,但假设你想在 x 处划分元素,如果它> 10,你可以简单地做

>>> df = [1,2,3,4,5,6]
>>> df = [1,2,30,40,5,6]
>>> if df[2]>10:
...     df[2]/=2
... 
>>> df
[1, 2, 15.0, 40, 5, 6]

Note the /= instead of your /.注意 /= 而不是 /。

The easiest approach, I think, is to use boolean indexing.我认为最简单的方法是使用布尔索引。 For example:例如:

df = pd.DataFrame(           # create dataframe
    20*np.random.rand(6, 4), 
    columns=list("ABCD"))
print(df)                    # print df
df[df>10]/=2                 # divide entries over 10 by 2
print(df)                    # print df

Result:结果:

           A          B          C          D
0   1.245686   1.443671  17.423559  17.617235
1  13.834285  10.482565   2.213459   9.581361
2   0.290626  14.082919   0.224327  11.033058
3   5.113568   5.305690  19.453723   3.260354
4  14.679005   8.761523   2.417432   4.843426
5  15.990754  12.421538   4.872804   5.577625

          A         B         C         D
0  1.245686  1.443671  8.711780  8.808617
1  6.917143  5.241283  2.213459  9.581361
2  0.290626  7.041459  0.224327  5.516529
3  5.113568  5.305690  9.726862  3.260354
4  7.339503  8.761523  2.417432  4.843426
5  7.995377  6.210769  4.872804  5.577625

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM