如何对np.select()进行默认选择,使其成为数组,序列或数据框的先前值

问题描述 投票:0回答:1

我正在使用np.select()构造一个ndarray,值取决于某些条件,其值为1,-1或0。这些都可能无法满足,因此我需要一个默认值。我希望这个值是数组在上一个索引中保存的值,如果有道理的话。我的朴素代码在名为“ total”的DataFrame的某些列上运行,并引发错误,如下所示:

condlist = [total.ratios > total.s_entry, total.ratios < total.b_entry, (total.ratios > total.b_entry) & (total.ratios < total.s_entry)]
choicelist = (-1, 1, 0)
pos1 = pd.Series(np.select(condlist, choicelist, pos1))

有没有一种方法可以解决我的要求?例如,让数组开始

1
1
0
-1
-1

然后第六个元素不满足任何条件,由于它是数组的最新值,因此其值默认为-1?

python pandas numpy numpy-ndarray
1个回答
0
投票

我不确定您是否会对这种解决方案感到满意,但是您可以分配一些默认值,然后在迭代时将其更改为所需的值:

x = np.arange(20)

condlist = [x < 4, np.logical_and(x > 8, x < 15), x > 15, True]
choicelist = (-1, 1, 0, None)
pos1 = pd.Series(np.select(condlist, choicelist, x))

for index, row in pos1.items():
    if row == None and index == 0:
        pass # Not sure what you want to do here
    elif row == None:
        pos1.at[index] = pos1.at[index-1]
© www.soinside.com 2019 - 2024. All rights reserved.