numpy中的条件句。如何使用pandas或numpy在数据帧中放入3个或更多?

2024-06-17 14:49:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我的语法有问题。我想买的时候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,) 

Tags: 代码gtdfband波段语法window级别
1条回答
网友
1楼 · 发布于 2024-06-17 14:49:51
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)

相关问题 更多 >