python - 数据框参数:为什么我的 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()
解决方案
您正在Tilt
使用总和ptf
但不返回修改后的ptf
DataFrame 设置全局变量。
推荐阅读
- azure-resource-manager - Azure 资源管理器模板
- javascript - socket.io 如何发送到以某些关键字开头的房间
- javascript - WebUsb 上的速度 1.2 mb/sec 正常吗?
- django-rest-framework - 使用 django rest 框架,如何为现有父对象添加新的嵌套子对象
- laravel - 如何从 laravel 中的数据库中删除数据?
- ios - 使用 IBDesignable 的水平虚线
- haskell - 使用 Aeson 对 Json 中的基本求和类型进行序列化
- android - 使用 Powermockito whenNew() 方法新建处理程序失败并抛出 NullPointerException
- python - 是否可以在 Keras LSTM 中使用具有不同行数的对象?
- google-chrome-extension - Chrome 扩展:getBackgroundPage 与 sendMessage。哪种方法更好?