[英]Get previous non-NaN value of a column in a pandas dataframe to calculate
我有以下 pd df 时间序列,其中有收盘价、确定何时打开 (1) 或关闭 (-1) position、position 的大小和总数(大小*关闭)的过滤器:
Date Close Filter O_Size O_Tot
1/5/2018 15.85 1 74 1172.9
1/8/2018 16.50 0
...
2/14/2018 16.49 0
2/15/2018 16.03 -1
...
当Filter的值为-1时,我想新建一个列C_Tot = Close * O_Size,取之前的size值不是NaN的时候。
Date Close Filter O_Size O_Tot C_Tot
1/5/2018 15.85 1 74 1172.9
1/8/2018 16.50 0
...
2/14/2018 16.49 0
2/15/2018 16.03 -1 1186.22
...
我想知道我是否可以在没有循环的情况下做到这一点。
干杯
我使用您在此处提供的有限数据创建了它。在使用它之前将所有空单元格设置为 nan。
import pandas as pd
import numpy as np
v=[["1/5/2018",15.85 , 1, 74 , 1172.9],
["1/8/2018",16.50 ,0 ,np.nan,np.nan],
["2/14/2018" , 16.49, 0 ,np.nan,np.nan] ,
["2/15/2018", 16.03, -1 ,np.nan,np.nan]]
df=pd.DataFrame(v,columns=["Date","Close","Filter","O_Size","O_Tot"])
tmp = df[df.Filter==-1]
def func(x):
spl = df.iloc[:x.name,:]
val = spl.iloc[spl["O_Size"].last_valid_index()].O_Size*x.Close
return val
tmp["C_Tot"] = tmp.apply(func,axis=1)
res = pd.concat([df,tmp["C_Tot"]],axis=1)
output
Date Close Filter O_Size O_Tot C_Tot
0 1/5/2018 15.85 1 74.0 1172.9 NaN
1 1/8/2018 16.50 0 NaN NaN NaN
2 2/14/2018 16.49 0 NaN NaN NaN
3 2/15/2018 16.03 -1 NaN NaN 1186.22
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.