首页 > 解决方案 > Python - 在 FOR 循环中按列将数据帧附加在一起

问题描述

我有一个 FOR 循环,它创建一个 3 列的数据框,然后重复该过程 n 次。每个循环的列名都不同,因此我想将所有数据帧连接到列上的一个数据帧中,而不是行上。所以数据框会很宽。我试图在 FOR 循环之前创建一个空数据帧,然后在 FOR 循环内将数据帧连接在一起。但这不起作用。dfmaster 只保留数据的最后一次 FOR 循环迭代。有人可以帮我将所有数据框连接在一起。

appended_data = pd.DataFrame()

for col in colnames:
    
    df[col+'_RR'] = df['p_'+col] - df['r2500_ret']

    df[col+'_sec_rr'] = df['ret'] - df[col+'_RR']
  
    # Calculate Correlation
    dfcorr = df.groupby('symbol').apply(lambda v: v[col+'_sec_rr'].corr(v[col+'_RR'])).to_frame().rename(columns={0:col+'_correlation'})

    # Calculate Slope
    dfslopedf = df[df[col+'_sec_rr'].notna()]
    dfslope = dfslopedf.groupby('symbol').apply(lambda v: stats.linregress(v[col+'_RR'], v[col+'_sec_rr'])[0]).to_frame().rename(columns={0:col+'_slope'})

    # Combine Correlation and Slope Dataframes
    dfadj = dfcorr.join(dfslope)

    # Calculate adj column
    dfadj[col+'_adj'] = dfadj[col+'_correlation'] *((abs(dfadj[col+'_slope'])+1)/2)

    # Creates a date column based on the max date value from the dataframe
    dfadj['date'] = df.index.get_level_values('date').max()

    # Reset index and add date & symbol
    dffinal = dfadj.reset_index(drop = False)
    dffinal = dffinal.set_index(['date', 'symbol'])

    dfmaster = pd.concat([appended_data, dffinal], axis=1)

样本输入数据:

在此处输入图像描述

电流输出(不正确!):

在此处输入图像描述

所需的输出将超过 25+ 列宽。

标签: pythonfor-loopjoinmergeconcatenation

解决方案


推荐阅读