计算差异选定元素熊猫数据框列

时间:2020-07-18 14:25:01

标签: pandas dataframe

需要代码逻辑来检查错误定价,并且第一次大于6,它将采用该时间戳记Value,我们将其称为“ TS1”。然后它将检查连续的m enter image description here ispricing> 6,这是第一次将错误定价从“是”转到“否”,将错误定价的时间戳记设为“否”,并将其称为“ TS2”。

然后做TS2-TS1

1 个答案:

答案 0 :(得分:0)

df=pd.DataFrame(data={'ts':list(range(1,14)),
                      'mp':[0,0,1,1,1,0,0,1,1,0,0,1,0]}) # your data
df.loc[df.mp.diff(1)==1, 'ts1'] = df.ts  # TS1
df.loc[df.mp.diff(1)==-1, 'ts2'] = df.ts  # TS2
df=df[~(df.ts1.isna())|~(df.ts2.isna())] # keep only rows with changes
df.loc[~df.ts2.isna(), 'delta'] = df.ts2 - df.ts1.shift(1)  # TS2-TS1
print (df)

    ts  mp   ts1   ts2  delta
2    3   1   3.0   NaN    NaN
5    6   0   NaN   6.0    3.0
7    8   1   8.0   NaN    NaN
9   10   0   NaN  10.0    2.0
11  12   1  12.0   NaN    NaN
12  13   0   NaN  13.0    1.0