numpy中的条件.如何使用panda或numpy在数据帧中放入3个或更多



我的语法有问题。我想在LastPrice将>到较低波段时买入,并在LastPrice==sma级别时卖出,如果这是真的,我想把结果放在一列中:"买入"它不像这样放"卖出">

我的代码:

df['LastPrice'].dropna(inplace=True)
sma = df['LastPrice'].rolling(window=20).mean()
rstd = df['LastPrice'].rolling(window=20).std()
df['upper_band'] = sma + 2 * rstd
df['lower_band'] = sma - 2 * rstd
df['laseñalota'] = np.where((df['LastPrice'] > df['lower_band'],"Buy") & (df['LastPrice'] == sma), "Sell")

错误为:

operands could not be broadcast together with shapes (2,) (4508,) 
df['laseñalota'] = np.where(df['LastPrice'] > df['lower_band'], 'Buy', 
np.where(df['LastPrice'] <= sma, 'Sell', 'Do Nothing'))

根据@user3483203的建议,如果您有更多的条件,并且希望在代码中的单独一行中更准确地反映它,那么也可以使用np.select。参见以下代码示例:

condlist = [df['LastPrice'] > df['lower_band'], df['LastPrice'] <= sma]
choicelist = ['Buy', 'Sell']
df['new_laseñalota'] = np.select(condlist, choicelist)

最新更新