我有一个数据框:
类型:体积:
问题10
问题20
T NA
问题10
T NA
T NA
问题10
...
当我得到每个类型的时候' T'在row [i],我想找到Q [i-1] - Q [i + 1]的对应值(即关闭到T,高于和低于T的Q值)
l = len(table)
dMidP = np.zeros((l,1))
check = np.zeros((l,1))
MidPrice = table['MidPrice']
Type = table['Type']
for i in range(2,l-1):
if Type[i] == 'Quote':
dMidP[i] = np.log(MidPrice[i])-np.log(MidPrice[i-1])
check[i] = 0
elif Type[i] == 'Trade' and Type[i+1] == 'Trade' :
dMidP[i] = np.log(MidPrice[i+2])- np.log(MidPrice[i-1])
check[i] = 2
elif Type[i] == 'Trade' and Type[i-1] == 'Trade' :
dMidP[i] = np.log(MidPrice[i+1])- np.log(MidPrice[i-2])
check[i] = 2
else :
dMidP[i] = np.log(MidPrice[i+1])- np.log(MidPrice[i-1])
check[i] = 1
答案 0 :(得分:2)
我可以这样做的一种方法是使用ffill()和bfill()创建一对临时列,然后将这些列减去fillna。
df.assign(Volume=df.assign(fnaf=df.Volume.ffill(), fnab=df.Volume.bfill())
.eval('Vnew = fnaf - fnab', inplace=False)
.pipe(lambda x: x.Volume.fillna(x.Vnew)))
输出:
Type Volume
0 Q 10.0
1 Q 20.0
2 T 10.0
3 Q 10.0
4 T 0.0
5 T 0.0
6 Q 10.0
编辑添加日志功能:
df.assign(Volume=df.assign(fnaf=np.log(df.Volume.ffill()), fnab=np.log(df.Volume.bfill()))
.eval('Vnew = fnaf - fnab', inplace=False)
.pipe(lambda x: x.Volume.fillna(x.Vnew)))