问题描述
st
0 74
1 91
2 105
3 121
4 136
5 157
此Serie的数据是累积总和的结果,所以我想知道pandas函数是否可以“撤消”该过程,并返回新的Serie像:
st result
0 74 74
1 91 17
2 105 14
3 121 16
4 136 15
5 157 21
result[0] = st[0],but after result[i] = st[i]-st[i-1].
这似乎很简单(也许我错过了一篇帖子),但是我什么也没找到...
解决方法
使用Series.diff
并将第一个缺失值替换为Series.fillna
,然后将其转换为整数:
df['res'] = df['st'].diff().fillna(df['st']).astype(int)
print (df)
st res
0 74 74
1 91 17
2 105 14
3 121 16
4 136 15
5 157 21