Skip to main content
 首页 » 编程设计

python之numpy 中的条件语句。如何使用 pandas 或 numpy 将 3 个或更多个放入我的数据框中

2024年12月31日10java哥

我的语法有问题。我想在 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的建议,如果你有更多的条件并且想在代码中单独的一行中更准确地反射(reflect)它,也可以使用np.select。例如,请参见以下代码:

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