使用布尔逻辑合并和过滤一个数据框的多列

时间:2018-10-04 07:27:21

标签: python pandas dataframe filter boolean

目标:在过滤掉“ False”值的同时,将买/卖/中性/错误指标输出到单个df [column]。指标基于下面的数据框列,然后用布尔语句来表示:

df['sma_10'] = pd.DataFrame(ta.SMA(df['close'], timeperiod=10), dtype=np.float, columns=['close'])      
df['buy'] = pd.DataFrame(df['close'] > df['sma_10'], columns=['buy'])   
df['buy'] = df['buy'].replace({True: 'BUY'})        
df['sell'] = pd.DataFrame(df['close'] < df['sma_10'], columns=['sell'])     
df['sell'] = df['sell'].replace({True: 'SELL'})         
df['neutral'] = pd.DataFrame(df['close'] == df['sma_10'], columns=['neutral'])       
df['neutral'] = df['neutral'].replace({True: 'NEUTRAL'})        
df['error'] = pd.DataFrame((df['buy'] == False) & (df['sell'] == False) & (df['neutral'] == False), columns=['Error'])      
df['error'] = df['error'].replace({True: 'ERROR'})

df的当前输出

buy  sell  Neutral Error
False False False ERROR
BUY False False False
False SELL False False
False False NEUTRAL False

所需的df输出

Indicator
ERROR
BUY
SELL
NEUTRAL

尝试与方法: 第一种方法:合并所有购买/出售/中立/错误列,并尝试删除“假”值。数据框仅在出错前重复一次。

df['sma_10_indic']=[df['buy'].astype(str)+df['sell'].astype(str)+df['neutral'].astype(str)+df['error'].astype(str)].drop("False")

我尝试了if&elif的子例程,例如: 此方法还会在第一个索引

之前出错
df['buy'] = pd.DataFrame(df['close'] > df['sma_10'])
df['sell'] = pd.DataFrame(df['close'] < df['sma_10'])
df['neutral'] = pd.DataFrame(df['close'] == df['sma_10'])
error = ((buy == False) and (sell == False) and (neutral == False))
if (df['buy'] == "True"):
   df['sma_10_indic'] = pd.DataFrame("BUY",columns=['indicator'])
elif (df['sell'] == "True"):
   df['sma_10_indic'] = pd.DataFrame("SELL",columns=['indicator'])
elif (df['neutral'] == "True"):
   df['sma_10_indic'] = pd.DataFrame("NEUTRAL",columns=['indicator'])
elif (error == True):
   df['sma_10_indic'] = pd.DataFrame("ERROR",columns=['indicator'])

我不确定前进的方向,在这条路上我一直不停地朝着墙打了14个小时,但没有前进的路。我也尝试过创建另一个单独的数据框,并通过concat合并它们,但由于布尔值而没有运气。我对python和pandas / dataframes比较陌生,所以请耐心等待。预先谢谢您!

1 个答案:

答案 0 :(得分:0)

使用numpy.select

m1 = df['close'] > df['sma_10']
m2 = df['close'] < df['sma_10']
m3 = df['close'] == df['sma_10']

df['Indicator'] = np.select([m1, m2, m3], ['BUY','SELL','NEUTRAL'], 'ERROR')