Python - For循环

Jor*_* M. 2 python for-loop pandas

我在stackoverflow上尝试了几种解决方案,但仍无法解决问题.因为我刚开始编程,所以它可能是一个简单的解决方案.

情况: 目前正在开发名为'dataset'的Pandas数据框,其中包含zscore列.我想确定高于3.00的单元格,以便将zscore的值设置为3.00.另一方面,我希望将zscore中-3.00以下的值更改为-3.00.

代码:

maxzscore = 3.00
minzscore = -3.00

print ('Set the max zscore:', maxzscore)
print ('Set the min zscore:', minzscore)

for value in dataset.zscore:
    # identify zscore above maxzscore
    if value > maxzscore:
        (dataset['zscore'].replace(3.00))
    # identify zscore below minzscore
    elif (dataset['zscore'] < minzscore):
        (dataset['zscore'].replace(-3.00))
    # do nothing
    else:
        pass

   dataset.to_excel('dataset.xls')
Run Code Online (Sandbox Code Playgroud)

问题: 代码循环遍历数据的时间非常长,效率不高.因此,我想知道如何缩短处理时间并改进代码.

非常感谢帮助.

Ste*_*n G 6

不需要循环..只需使用clip()方法:

   dataset['zscore'] = dataset['zscore'].clip(-3.0, 3.0)
Run Code Online (Sandbox Code Playgroud)