简体   繁体   English

如何在 Pandas 中跳过 Nan 来计算上一行和下一行的总和

[英]How to do sum previous and next row with skipping Nan in Pandas

I have one column in my Dataframe and I am trying to calculate the energy loss with formula.我的数据框中有一列,我正在尝试用公式计算能量损失。 Problem is that I want to use only two valid rows each time where values are not NaN.问题是每次值不是 NaN 时,我只想使用两个有效行。 Energy is the input column and looking for something like loss column.能量是输入列,正在寻找类似损失列的内容。

Energy活力 loss失利
NaN Nan
NaN Nan
NaN Nan
4 4 Nan
NaN Nan
3 3 1/2(4^2-3^2) 1/2(4^2-3^2)
NaN Nan
11 11 Nan
3 3 1/2(3^2-11^2) 1/2(3^2-11^2)
NaN NaN
14 14 Nan

I tried Lambda custom function but not able to send the next row.我尝试了 Lambda 自定义函数,但无法发送下一行。

Try something like this:尝试这样的事情:

df = pd.DataFrame({'Energy':[4,None,3,None,11,3,None,14]})
energy = df.Energy.dropna()
def my_loss(series):
    return 1/2*(series.iloc[0]**2-series.iloc[1]**2)
loss = energy.rolling(2).apply(my_loss)
df['loss'] = loss[1::2]  # skip half of the results

Basically you apply your custom function in the rolling of the droped nan energy, and then merge it again with your df.基本上,您将自定义函数应用于下降的 nan 能量的滚动,然后将其再次与您的 df 合并。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM