基于数据帧中其他列的值执行计算的最快方法是什么?

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

我有df,必须应用此公式:

enter image description here

到每一行,然后添加新系列(作为新列)。

现在我的代码是:

 new_col = deque()
    for i in range(len(df)):
        if i < n:
            new_col.append(0)
        else:
            x = np.log10(np.sum(ATR[i-n:i])/(max(high[i-n:i])-min(low[i-n:i])))
            y = np.log10(n)
            new_col.append(100 * x/y)
    df['new_col'] = pd.DataFrame({"new_col" : new_col})

ATR,high,low从我现有df的列中获得。但是这种方法很慢。有没有更快的方法来执行任务?谢谢。

python numpy dataframe logarithm arithmetic-expressions
1个回答
0
投票

没有示例数据,我无法测试以下内容,但应该可以使用:

tmp_df = df.rolling(n).agg({'High':'max', 'Low':'min', 'ATR':'sum'})

df['new_col'] = (100*np.log10(tmp_df['ATR'])) / (tmp_df['High'] - tmp_df['Low']) / np.log10(n)

df['new_col'] = df['new_col'].shift().fillna(0)
© www.soinside.com 2019 - 2024. All rights reserved.