determine the coordinates where two pandas time series cross, and how many times the time series cross

非 Y 不嫁゛ 提交于 2019-12-05 12:52:40

Here is a quick try using pandas.

import pandas as pd
import numpy as np

df = pd.DataFrame({"A":[1,2,3,4,5], "B":[0.5,3,1,1,6]})
print df

Which gives

   A    B
0  1  0.5
1  2  3.0
2  3  1.0
3  4  1.0
4  5  6.0

Then use the difference

df['difference'] = df.A - df.B

df['cross'] = np.sign(df.difference.shift(1))!=np.sign(df.difference)
np.sum(df.cross)-1

You need the -1 for the first row in which the shift(1) will return NaN

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!