如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
>>> import pandas as pd
>>> import numpy as np
# 生成模拟数据
>>> df = pd.DataFrame({ 'a' :np.random.randint( 1 , 100 , 10 ),\
'b' :np.random.randint( 1 , 100 , 10 )},\
index = map ( str , range ( 10 )))
>>> df
a b
0 21 54
1 53 28
2 18 87
3 56 40
4 62 34
5 74 10
6 7 78
7 58 79
8 66 80
9 30 21
# 纵向一阶差分,当前行减去上一行
>>> df.diff()
a b
0 NaN NaN
1 32.0 - 26.0
2 - 35.0 59.0
3 38.0 - 47.0
4 6.0 - 6.0
5 12.0 - 24.0
6 - 67.0 68.0
7 51.0 1.0
8 8.0 1.0
9 - 36.0 - 59.0
# 横向一阶差分,当前列减去左边的列
>>> df.diff(axis = 1 )
a b
0 NaN 33.0
1 NaN - 25.0
2 NaN 69.0
3 NaN - 16.0
4 NaN - 28.0
5 NaN - 64.0
6 NaN 71.0
7 NaN 21.0
8 NaN 14.0
9 NaN - 9.0
# 纵向二阶差分
>>> df.diff(periods = 2 )
a b
0 NaN NaN
1 NaN NaN
2 - 3.0 33.0
3 3.0 12.0
4 44.0 - 53.0
5 18.0 - 30.0
6 - 55.0 44.0
7 - 16.0 69.0
8 59.0 2.0
9 - 28.0 - 58.0
# 纵向二阶差分,丢弃空值
>>> df.diff(periods = 2 ).dropna()
a b
2 - 3.0 33.0
3 3.0 12.0
4 44.0 - 53.0
5 18.0 - 30.0
6 - 55.0 44.0
7 - 16.0 69.0
8 59.0 2.0
9 - 28.0 - 58.0
|
以上这篇Python使用pandas对数据进行差分运算的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/oh5W6HinUg43JvRhhB/article/details/78349014