编辑:
我在 Pandas 数据框 df 中有一个金融投资组合,其中索引是日期,每个日期我有多个金融股票。
例如数据框:
Date Stock Weight Percentile Final weight
1/1/2000 Apple 0.010 0.75 0.010
1/1/2000 IBM 0.011 0.4 0
1/1/2000 Google 0.012 0.45 0
1/1/2000 Nokia 0.022 0.81 0.022
2/1/2000 Apple 0.014 0.56 0
2/1/2000 Google 0.015 0.45 0
2/1/2000 Nokia 0.016 0.55 0
3/1/2000 Apple 0.020 0.52 0
3/1/2000 Google 0.030 0.51 0
3/1/2000 Nokia 0.040 0.47 0
每当 Percentile
大于 0.7
Weight
的值来创建 Final_weight
现在我想让它更复杂一些,我仍然希望在 Percentile > 0.7
时将 Weight
分配给 Final_weight
,但是在这个日期之后(在未来的任何时候),当股票 Percentile
不是 >0.7
时,我们仍然会得到一个权重,而不是变成 0,只要股票 Percentile
高于 0.5
(即持仓时间超过一天)。
然后,如果股票低于 0.5
(在不久的将来),则 Final_weight 将变为 0
。
例如从上面修改的数据框:
Date Stock Weight Percentile Final weight
1/1/2000 Apple 0.010 0.75 0.010
1/1/2000 IBM 0.011 0.4 0
1/1/2000 Google 0.012 0.45 0
1/1/2000 Nokia 0.022 0.81 0.022
2/1/2000 Apple 0.014 0.56 0.014
2/1/2000 Google 0.015 0.45 0
2/1/2000 Nokia 0.016 0.55 0.016
3/1/2000 Apple 0.020 0.52 0.020
3/1/2000 Google 0.030 0.51 0
3/1/2000 Nokia 0.040 0.47 0
每天的投资组合都不同,并不总是拥有与前一天相同的股票。
最佳答案
这个解决方案更明确,更少 pandas-esque,但它只涉及一次遍历所有行而不创建大量临时列,因此可能更快。它需要一个额外的状态变量,我将它包装到一个闭包中,这样就不必创建一个类了。
def closure():
cur_weight = {}
def func(x):
if x["Percentile"] > 0.7:
next_weight = x["Weight"]
elif x["Percentile"] < 0.5 :
next_weight = 0
else:
next_weight = x["Weight"] if cur_weight.get(x["Stock"], 0) > 0 else 0
cur_weight[x["Stock"]] = next_weight
return next_weight
return func
df["FinalWeight"] = df.apply(closure(), axis=1)
关于python - Pandas :分配具有多个条件和日期阈值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43791970/