[英]Subtract previous row value from the current row value in a Pandas column
I have a pandas column with the name 'values' containing respective values 10 15 36 95 99
. 我有一个pandas列,名称为“ values”,其中包含各自的值10 15 36 95 99
。 I want to subtract the each value from the next value so that I get the following format: 10 5 21 59 4
我想从下一个值中减去每个值,以便获得以下格式: 10 5 21 59 4
I've tried to solve this using a for loop that loops over all the data-frame but this method was time consuming. 我试图使用一个遍历所有数据帧的for循环来解决此问题,但是这种方法很耗时。
for i in range(1,length_colulmn):
df['value'].iloc[i] = df['value'].iloc[i]-df['value'].iloc[i-1]
Is there a straightforward method the dataframe functions to solve this problem quickly? 数据框是否有一种直接的方法可以快速解决此问题? The output we desire is the following: 我们期望的输出如下:
['input']
11
15
22
27
36
69
77
['output']
11
4
7
5
9
33
8
Use pandas.Series.diff
with fillna
: 将pandas.Series.diff
与fillna
pandas.Series.diff
使用:
import pandas as pd
s = pd.Series([11,15,22,27,36,69,77])
s.diff().fillna(s)
Output: 输出:
0 11.0
1 4.0
2 7.0
3 5.0
4 9.0
5 33.0
6 8.0
dtype: float64
You can use the pythonic shift
function. 您可以使用pythonic shift
函数。 see how I did it. 看看我是怎么做到的。 Let me know if it works. 让我知道它是否有效。
Code here: 代码在这里:
import pandas as pd
df = pd.DataFrame({ 'input': [11, 15, 22, 27, 36, 69, 77]})
df['output']=df['input'] -df['input'].shift(1)
df
#df['output'].dropna()
Explanation: 说明:
Result: 结果:
input output
0 11 NaN
1 15 4.0
2 22 7.0
3 27 5.0
4 36 9.0
5 69 33.0
6 77 8.0
you can remove NaN
with dropna()
. 您可以使用dropna()
删除NaN
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.