gpt4 book ai didi

python - 使用 boolean 逻辑合并和过滤一个数据帧的多列

转载 作者:太空宇宙 更新时间:2023-11-03 21:43:55 25 4
gpt4 key购买 nike

目标:将买入/卖出/中性/错误指标输出到单个 df[column],同时过滤掉“False”值。指标基于以下数据框列,然后用 boolean 语句制定:

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

尝试与方法:第一种方法:合并所有买入/卖出/中性/错误列并尝试删除“False”值。 Dataframe 在出错之前仅迭代一次。

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 合并它们,但由于 boolean 值而没有运气。我对 python 和 pandas/dataframes 比较陌生,所以请耐心等待。预先感谢您!

最佳答案

使用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')

关于python - 使用 boolean 逻辑合并和过滤一个数据帧的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52641263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com