python - 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+ 列宽。
解决方案
推荐阅读
- javascript - 如何将本地 json 文件渲染成 HTML 和浏览器
- bash - How do I not have a duplicated custom bash script directory on my machine and add it as a link that is picked up with PATH?
- java - Java Web SQL: No suitable driver found for jdbc, but driver is added in project and code works fine local
- mysql - MYSQL Random Entry with weight fails
- laravel - Two models, two fields, return preferred if present
- jenkins - 无法在 Jenkins 中通过 SSH 连接远程服务器
- javascript - 对带有 role='button' 的 div 元素的点击不起作用
- javascript - 将 X,Y 像素转换为经度和纬度
- php - 应该如何预先加载属性?
- perl - perl 脚本中的 Tcl 调用