基于Pandas上的当前列生成列的最佳实践,而不存在潜在的ValueError冲突?

2024-04-27 03:42:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试基于数据帧中的当前列生成新列。你知道吗

df.loc[df[ss] < 0.2, flagName] = +1

Note: df[ss] is a column with floating point data.

df有100行时,这工作得很好,但是当我向df添加额外的行并使其达到500行时,我得到了以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我所做的是不是因为某种原因而成为了一个坏习惯?你知道吗


编辑:其他详细信息:

此函数计算“慢随机”信号。df中的“low”、“high”和“close”列都是浮点值。我想不出是什么原因导致出现这个错误。你知道吗

def calc_slowStochastic(st, df):
    lowest = 'low_' + str(st[0]) + str(st[1])
    highest = 'high_' + str(st[0]) + str(st[1])
    stochasticK = 'K_' + str(st[0]) + str(st[1])
    stochasticD = 'D_' + str(st[0]) + str(st[1])
    stochasticSlow = 'Slow_' + str(st[0]) + str(st[1])

    df[lowest] =  df['low'].rolling(window=st[0]).min()
    df[highest] = df['high'].rolling(window=st[0]).max()
    df[stochasticK] = 100*(df['close'] - df[lowest]) / (df[highest] - df[lowest])
    df[stochasticD] = df[stochasticK].rolling(window=st[1]).mean()
    df[stochasticSlow] = df[stochasticD].rolling(window=st[1]).mean()

    flagName = 'oscStochastic' + str(st[0]) + str(st[1])
    df[flagName] = 0
    df.loc[df[stochasticSlow] < 0.2, flagName] = +1
    df.loc[df[stochasticSlow] > 0.8, flagName] = +1

    return df

Tags: dfwindowssloclowsthighrolling