基于数组中的值的动态numpy条件

dddzy1tm  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(95)

我试图找出如何以动态的方式使用np.where,我选择一些预定义的值,将它们传递给一个函数,让它们创建条件。理想情况下,我希望用几个逻辑运算符创建长条件。
在下面的代码中,我愚蠢地尝试使用字符串:
cond_arr[1]['cond']作为一个逻辑运算符,来说明我想要的,因为我不知道如何进行这个?
有没有一个优雅的(或只是工作)的方式来创造这些动态的条件?

import numpy as np
import pandas as pd
import random
from datetime import datetime, timedelta

data = {
    'open': [random.uniform(50, 100) for _ in range(30)],
    'high': [random.uniform(100, 150) for _ in range(30)],
    'low': [random.uniform(25, 50) for _ in range(30)],
    'close': [random.uniform(50, 100) for _ in range(30)],
    'volume': [random.randint(1000, 10000) for _ in range(30)],
    'datetime': [datetime(2023, 10, 1, 0, 0) + timedelta(hours=i) for i in range(30)]
}

df = pd.DataFrame(data)

# The meat and potatoes

indicators = [{"ind": "open"},{"ind": "rsi"}, {"ind": "macd"}]
conds = [{"cond": "<"}, {"cond": ">"}, {"cond": "=="}, {"cond": "and"}, {"cond": "or"}]
values = [{"val": 10}, {"val": 100}, {"val": 15}, {"val": 17}, {"val": 18}, {"val": 7}]

def create_condition(cond_array):
    print(f'{cond_array[0]["ind"]}')  # Use double curly braces to escape
    
    #df["signal"] = np.where(df["open"] > 10, 1, -1) <-- what i want to do below
    df["signal"] = np.where(df[f'{cond_array[0]["ind"]}'] cond_arr[1]['cond']  df[f'{cond_array[2 ["val"]}'], 1, -1)

selected_conds = [indicators[0],conds[0],values[0]]

create_condition(selected_conds)

字符串

pw136qt2

pw136qt21#

使用pd.eval计算动态表达式:

def make_clause(df, col_d, cond_d, val_d):
    col, cond, val = col_d['ind'], cond_d['cond'], val_d['val']
    df["signal"] = np.where(pd.eval(f'df.{col} {cond} {val}',
                                    target=df), 1, -1)

selected_conds = [indicators[0], conds[0], values[0]]
make_clause(df, *selected_conds)

字符串
如果目标列名包含空格,则使用f'df["{col}"] {cond} {val}'作为表达式。

9jyewag0

9jyewag02#

使用operators,为了方便Map,通过扁平化字典列表创建字典d

from collections import ChainMap

selected_conds = [indicators[0],conds[0],values[0]]
d = dict(ChainMap(*selected_conds))
print (d)
{'val': 10, 'cond': '<', 'ind': 'open'}
   

import operator

ops = {'>': operator.gt,
        '<': operator.lt,
       '>=': operator.ge,
       '<=': operator.le,
       '==': operator.eq,
        '!=': operator.ne,
        'and': operator.and_,
        'or': operator.or_}

#df["signal"] = np.where(df["open"] < 10, 1, -1)
df["signal"] = np.where(ops[d['cond']](df[d['ind']], d['val']), 1, -1)

字符串

相关问题