Posted in Python onDecember 22, 2018
如下所示:
>>> 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对数据进行差分运算的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。
Python使用pandas对数据进行差分运算的方法
- Author -
Python_小屋声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@