首页 > 解决方案 > 数据框参数:为什么我的 df 上的更改是本地的?

问题描述

我有一个函数应该在 df 上实现一些转换和计算,代码会运行,但是一旦完成,df 就会和以前一样。

编辑:当我删除第 2 行(pd.merge)时问题得到解决,但我想了解原因。

def Tilt_contribution(ptf, data_factors, data_universe, Sample_size_adjustment:bool):
    ptf['ActiveWeight'] = ptf['PortfolioWeight']- ptf['BenchmarkWeight']
    ptf = pd.merge(ptf, data_factors, on = ['ISIN','SecurityName'], how = 'left' )
    sample_size_adj = 1 #initialisation
    if Sample_size_adjustment == True:
        sample_size_adj = Sample_size_adj(ptf)
    for column in factor_list:
        #Weighted std
        universe_wght_std = Universe_weighted_std(data_universe, column)
        #Benchmark weighted average
        benchmk_wght_avg = Benchmark_weighted_avg(ptf, column)
        #Tilt Contrib   
        col_index = ptf.columns.get_loc(column)
        ptf.insert(col_index+1, column + ' Tilt Contribution', 0)    
        for idx in ptf.index:
            tilt_cont = (ptf.at[idx, column] - benchmk_wght_avg)*ptf.at[idx, 'ActiveWeight']/(sample_size_adj * universe_wght_std)
            if math.isnan(tilt_cont):
                tilt_cont=0
            ptf.at[idx, column + ' Tilt Contribution'] = tilt_cont
    global Tilt
    Tilt = ptf.sum()

标签: pythonpandas

解决方案


您正在Tilt使用总和ptf但不返回修改后的ptfDataFrame 设置全局变量。


推荐阅读