Pythonpandas如何处理操作

Python pandas how to deal with operations

我有以下问题,我不确定如何以可接受的性能解决。

示例:

我有一个列表,其中包含 2 个日期之间的所有股票收盘价,比方说 close_price = [1, 2, 5, 3, 10, 1]

而且我还有一个只有 True 和 False 的数组,如果它是单买则有 True。 buy_ind = [False, True, False, False, True, False]

所有滥用行为都在 pandas.DataFrame 中找到。

如果没有任何 for-loop 更可取,我怎么能说这样的话呢?

我想遍历 close_price 中在 buy_ind 中为真的所有元素(使用 np.where()),我想检查其中哪一个满足我的条件,并且然后去下一个。

最后,我将得到一个包含所有卖出信号的数组。

谁能告诉我如何在不使用 for 循环的情况下解决这个问题,而只是遍历所有数组并检查条件?或者这是唯一的方法?

更新:

示例:

df['close'] = [1, 4, 5, 3, 1, 2]
df['buy'] = [False, True, False, False, True, False]
df['indicator'] = [3.1, 5.3, 0.3, 0.1, 6.2, 8.5, 9.0]
df['sell'] = [False,False,False,False,False,False]

我要的是

  1. 循环总体'close'价格
  2. 在 'buy' 列中找到第一个为 True 的值(例如在我们的例子中是索引 1 中的值 4)
  3. 从同一索引上的 'indicator' 列获取值(在我们的例子中是 5.3)
  4. 检查以下哪些 'close' 价格将满足将使用 5.3 作为参数的某些条件
  5. 找到第一个满足条件的值时停止,设置'sell'的索引为True

例如:如果我们从 'close' 价格 4 开始,它相应地具有 indicator 的 5.3 值。我们将检查所有满足条件 (5.3) 的价格,例如,如果 'close' 索引 3 的价格 3 将满足 条件我们将从 'sell' True => [False,False,False,True,False,False]

设置索引
  1. 转到下一个收盘价并重复该过程

我对你想要的理解:

对于在 'buy' 列中具有 True 的每一行:

  • 函数根据 table
  • 中该行下方所有 'close' 值的列表检查该行的指示符
  • 函数returns我应该卖出的行的索引

然后:

  • 更新 'sell' 其索引由函数返回的所有行

输入:

df = pd.DataFrame()
df['close'] = [1, 4, 5, 3, 1, 2]
df['buy'] = [False, True, False, False, True, False]
df['indicator'] = [3.1, 5.3, 0.3, 0.1, 6.2, 8.5]
df['sell'] = [False,False,False,False,False,False]
def conditions(index, indicator, close_list):
    compare = indicator * 10
    for close in close_list[index+1:]:
        if compare > close:
            return index
        index += 1
    return -1

close_list = df['close'].tolist()
df['row_index'] = df.index

get_conds = lambda row: conditions(row['row_index'],row['indicator'],close_list) \
                        if row['buy'] \
                        else -1
df['sell_index'] = df.apply(get_conds, axis=1)
sell_inds = df['sell_index'].dropna().tolist()

df['sell'] = [ind in sell_inds for ind in df['row_index']]

>>> print(df)

   close    buy  indicator   sell  row_index  sell_index
0      1  False        3.1  False          0          -1
1      4   True        5.3  False          1           2
2      5  False        0.3   True          2          -1
3      3  False        0.1  False          3          -1
4      1   True        6.2  False          4           5
5      2  False        8.5   True          5          -1

显然您可以删除中间步骤列(row_index 和 sell_index)