如何使用多个数据集运行一个函数?

2024-10-05 10:57:30 发布

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

假设我得到了20组数据,我把它们读作df1,df2,df3,df4…df20。 (还有其他读取或存储数据帧的智能方法吗?)你知道吗

我的职能是:

def CalculateEMA(x,window):    
    sma = x.rolling(window, min_periods=window).mean()[:window]
    rest = x[window:]
    EMA_window=(pd.concat([sma, rest]).ewm(span=window,adjust=False).mean()).sum())

    return EMA_window

我希望返回所有20个数据帧的EMA,并存储为X。 所以我的最终输出是X=[x1,x2,x3,X,X,X,X,X…x20]。其中,x1是df1的EMA函数的和,x2是第二个数据集df2,依此类推。你知道吗


Tags: 数据方法rest智能windowmeandf1df2
2条回答

要读取文件夹中的所有csv文件,可以使用os函数

    import os
    path_to_dir='<your path>'
    filenames = os.listdir(path_to_dir)
    csvs=[f for f in filenames if f.endswith('csv')]
    out=[]
    for path in csvs:
        df=pd.read_csv(path)
        out.append(CalculateEMA(df,window))

如果将数据帧存储在列表中,则可以在数据帧中循环:

X=list()
list_df = [df1,df2,...,df20]
for df in list_df:
    X.append(CalculateEMA(df,window))

相关问题 更多 >

    热门问题