计算差异

时间:2018-03-07 16:37:59

标签: python numpy difference calculation

我有数据文件:file
我需要制作X差异(第1列),但仅限于第3列为1时。

import numpy as np

x,jump= np.loadtxt("data.svc",delimiter=' ',skiprows=1, usecols=(0,3),unpack=True)

resultX = list()

i=0
while (i<len(jump)):
    if jump[i] == 1:
        while(jump[i] == 1):
            i+=1
            temp = i
            resultX.append((abs(x[temp]-x[temp-1])))
    i+=1

print(resultX)

我的结果是:5,7,4,12,8,6,9,5,4,11这是错误的

我需要:5,7,4,8,6,5,4 correct results

1 个答案:

答案 0 :(得分:0)

我认为这会奏效:

>>> diff = np.diff(x)
>>> diff
array([ 5,  7,  4, 12,  4, 15,  8,  6,  9,  5,  5,  4,  5,  4, 11])
>>> 
>>> flag = np.diff(jump) + jump[1:]
>>> flag
array([ 1,  1,  1, -1,  0,  2,  1,  1, -1,  0,  0,  2,  1,  1, -1])
>>> 
>>> diff[flag == 1]
array([5, 7, 4, 8, 6, 5, 4])