当我在看到这个代码时,不是很了解np.diff()函数:
#计算以下列表中连续的天数。 import numpy as np from dateutil import parser dateString = ['Oct, 2, 1869', 'Oct, 10, 1869', 'Oct, 15, 1869', 'Oct, 20, 1869', 'Oct, 23, 1869'] dates = [parser.parse(i) for i in dateString] td = np.diff(dates) print(td) # [datetime.timedelta(days=8) datetime.timedelta(days=5) # datetime.timedelta(days=5) datetime.timedelta(days=3)] d = [i.days for i in td] print(d) # [8, 5, 5, 3]
还有矩阵运算时:
import numpy as np a=np.arange(10).reshape(5,2) print(a) ''' [[0 1] [2 3] [4 5] [6 7] [8 9]] ''' print(np.diff(a)) ''' [[1] [1] [1] [1] [1]] '''
现在说明一下这个函数的的用法和参数
numpy.diff(a, n=1,axis=-1)
参数:
1 a:输入矩阵 2 n:可选,代表要执行几次差值 3 axis:默认是最后一个
从输出结果可以看出,其实diff函数就是执行的是后一个元素减去前一个元素。