2017-09-21 114 views
1

我要添加新列(shop_yy['tt']在大熊貓數據幀用的if-else條件添加新列的現有列

for row in shop_yy['y']: 
     if row > shop_yy['3sigmaM'] or row < shop_yy['3sigmaL'] : 
      shop_yy['tt'] = pd.rolling_mean(shop_yy['y'],window=5) 
     else: 
      shop_yy['tt'] = shop_yy['y'] 

但我看到這個錯誤:

/usr/local/lib/python3.4/dist-packages/ipykernel_launcher.py:10: FutureWarning: pd.rolling_mean is deprecated for Series and will be removed in a future version, replace with 
    Series.rolling(center=False,window=3).mean() 
    # Remove the CWD from sys.path while we load stuff. 

--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-24-2d3ac684a2df> in <module>() 
    13  shop_yy['3sigmaL']=shop_yy['MA'] - 3*shop_yy['std'] 
    14  for row in shop_yy['y']: 
---> 15   if row > shop_yy['3sigmaM'] or row < shop_yy['3sigmaL'] : 
    16    shop_yy['tt'] = pd.rolling_mean(shop_yy['y'],window=5) 
    17   else: 

/usr/local/lib/python3.4/dist-packages/pandas-0.19.2-py3.4-linux-x86_64.egg/pandas/core/generic.py in __nonzero__(self) 
    915   raise ValueError("The truth value of a {0} is ambiguous. " 
    916       "Use a.empty, a.bool(), a.item(), a.any() or a.all()." 
--> 917       .format(self.__class__.__name__)) 
    918 
    919  __bool__ = __nonzero__ 

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

請幫助。

回答

1

最好的是與Series一起工作,而不是循環。通用的解決方案是通過使用條件或numpy.wheremask變化值:

m = (shop_yy['y'] > shop_yy['3sigmaM']) | (shop_yy['y'] < shop_yy['3sigmaL']) 

shop_yy['tt'] = np.where(m, pd.rolling_mean(shop_yy['y'],window=5), shop_yy['y']) 

或者:

shop_yy['tt'] = shop_yy['tt'].mask(m, pd.rolling_mean(shop_yy['y'],window=5)) 
+0

@cᴏʟᴅsᴘᴇᴇᴅ - 謝謝你。 – jezrael

+0

yes.it工作,但我想知道如何正確地做我的決定。我認爲這個問題是真/假,我在條件 – abyrwalg

+0

有問題,你比較'標量'與數組 - 然後輸出也是數組。所以如果得到數組'[[True,True,False,...]'那麼如果返回錯誤,因爲只需要標量True或False。 – jezrael