2017-05-03 148 views
2

我已經嘗試了幾種可用的解決方案,但仍無法解決此問題。因爲我剛開始編程,所以它可能是一個簡單的解決方案。Python - For循環

目前情況: 目前正在一個名爲'dataset'的包含zscore列的Pandas數據框上工作。我想確定高於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') 

問題: 代碼循環爲環形時間,這不是非常有效的數據。因此,我想知道如何縮短處理時間並改善代碼。

非常感謝幫助。

回答

6

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

dataset['zscore'] = dataset['zscore'].clip(-3.0, 3.0)