Skip to main content
 首页 » 编程设计

python之如何加速 pandas df.apply(可能使用 np.where 或 np_logical_and.reduce)

2024年10月01日23itcoder

我希望在 pandas 数据框中加快新列的生成,每行执行 myFunc() 的代码:

df = pd.DataFrame(data, columns=["EMA4","EMA4prior","EMA10","MACD"]) 
 
    def myFunc (self, row): 
           if ((row.EMA4 > row.EMA10) and (row.EMA4prior < row.EMA10) and (row.MACD > 0)): 
            return 0 
           if ((row.EMA4 < row.EMA10) and (row.EMA4prior > row.EMA10) and (row.MACD < 0)): 
            return 1 
        return -1 
 
self.df["position"] = self.df.apply(self.myFunc, axis=1) #apply this per each row 

该代码有效,但速度非常慢。我尝试了以下方法来改进它,但语法中的某些地方似乎有问题:

1.- 直接使用 numpy.where:

a=self.df["EMA4"].values 
b=self.df["EMA4prior"].values 
c=self.df["EMA10"].values 
d=self.df["MACD"].values 
self.df["position"] = np.where(((a > c)&(b < c)&(e > 0)),0,  
                       (np.where((a < c)&(b > c)&(d < 0)), 1, -1))  

2.- 使用 np.logical_and.reduce ,因为 np.logical_and 似乎是二元运算符(我有 3 个“and”要计算):

self.df["position"] = np.where(np.logical_and.reduce([(a > c),(b < c),(e > 0)]),0, 
                        (np.where(np.logical_and.reduce[(a < c),(b > c),(e < 0)]), 1, -1))  

我没有让它工作,它没有编译,我不确定哪里出了问题。

那么,有没有什么方法可以用 numpy 或其他方法来加速原始 myFunc() 以提高性能?

请您参考如下方法:

IIUC,你应该可以使用np.select:

cond = [(df.EMA4 > df.EMA10) & (df.EMA4prior < df.EMA10) & (df.MACD > 0),  
        (df.EMA4 < df.EMA10) & (df.EMA4prior > df.EMA10) & (df.MACD < 0)] 
result = [0,1] 
 
df['position'] = np.select(cond, result, -1)