【问题标题】:How to replace a loop that looks at multiple previous values with a formula in Python如何用 Python 中的公式替换查看多个先前值的循环
【发布时间】:2019-09-10 18:59:39
【问题描述】:

我的问题

我有一个循环,它使用基于其他列值的公式或列中的前一个值创建列,具体取决于条件(“距离新低的天数 == 0”)。在庞大的数据集上它真的很慢,所以我想摆脱循环并找到一个更快的公式。

当前工作代码

import numpy as np
import pandas as pd

csv1 = pd.read_csv('stock_price.csv', delimiter = ',')
df = pd.DataFrame(csv1)

for x in range(1,len(df.index)):
    if df["days from new low"].iloc[x] == 0:
        df["mB"].iloc[x] = (df["RSI on new low"].iloc[x-1] - df["RSI on new low"].iloc[x]) / -df["days from new low"].iloc[x-1]
    else:
        df["mB"].iloc[x] = df["mB"].iloc[x-1]

df

输入数据和预期输出

RSI on new low,days from new low,mB
0,22,0
29.6,0,1.3
29.6,1,1.3
29.6,2,1.3
29.6,3,1.3
29.6,4,1.3
21.7,0,-2.0
21.7,1,-2.0
21.7,2,-2.0
21.7,3,-2.0
21.7,4,-2.0
21.7,5,-2.0
21.7,6,-2.0
21.7,7,-2.0
21.7,8,-2.0
21.7,9,-2.0
25.9,0,0.5
25.9,1,0.5
25.9,2,0.5
23.9,0,-1.0
23.9,1,-1.0

尝试解决方案

def mB_calc (var1,var2,var3):
    df[var3]= np.where(df[var1] == 0, df[var2].shift(1) - df[var2] / -df[var1].shift(1) , "")
    return df

df = mB_calc('days from new low','RSI on new low','mB')  

首先,它给了我这个“TypeError:不能将序列乘以'float'类型的非整数”,其次我不知道如何将“ffill”合并到公式中。

知道我该怎么做吗?

干杯!

【问题讨论】:

  • 第二行提供的数据只有 2 个值。错字?
  • np.where(...) 是你的朋友
  • IcedLance 感谢现场。我刚刚纠正了它。波尔卡,我尝试了我现在放入帖子的位置,但我没有任何快乐

标签: python database pandas loops


【解决方案1】:

试试这个:

df["mB_temp"] = (df["RSI on new low"].shift() - df["RSI on new low"]) / -df["days from new low"].shift()
df["mB"] = df["mB"].shift()
df["mB"].loc[df["days from new low"] == 0]=df["mB_temp"].loc[df["days from new low"] == 0]
df.drop(["mB_temp"], axis=1)

还有np.where:

df["mB"] = np.where(df["days from new low"]==0, df["RSI on new low"].shift() - df["RSI on new low"]) / -df["days from new low"].shift(), df["mB"].shift())

【讨论】:

  • 感谢您的帖子。它在“距离新低的天数”== 0 但所有其他行都是“NaN”的行上返回正确的值。我添加了 df['mB'] = df['mB'].ffill() 到最后,现在似乎可以工作了。但是,我有额外的列 mB_Temp 这不是理想的
  • 我认为您也需要将 .loc 添加到正确的部分:df["mB"].loc[df["days from new low"] == 0]=df["mB_temp"].loc[df["days from new low"] == 0]
  • 你知道我如何使用 np.where 重写吗?
  • 我添加了np.where 版本。另外 - 你把mB_temp放在我原始代码的最后一行。
猜你喜欢
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
  • 2023-02-03
  • 2021-12-29
  • 1970-01-01
  • 2023-01-02
  • 2023-03-19
相关资源
最近更新 更多