Python 直线交点
我有一个pandas数据框,其中每列表示从1到0的递减行的y值,索引表示x值。现在我感兴趣的是找到这些线和给定常数(线性插值)之间的交点 所需输出的示例:Python 直线交点,python,pandas,line-intersection,Python,Pandas,Line Intersection,我有一个pandas数据框,其中每列表示从1到0的递减行的y值,索引表示x值。现在我感兴趣的是找到这些线和给定常数(线性插值)之间的交点 所需输出的示例: >>> df = pd.DataFrame({'y1': [1, .7, .4, .1, 0], 'y2': [1, .9, .7, .3, 0], 'y3': [1, .6, .3, .2, 0],
>>> df = pd.DataFrame({'y1': [1, .7, .4, .1, 0],
'y2': [1, .9, .7, .3, 0],
'y3': [1, .6, .3, .2, 0],
'y4': [1, .7, .5, .3, 0]}, index=[0, 10, 20, 30, 40])
>>> xs = get_intersection(df, .5)
>>> xs
{'x1': 16.6667, # = scipy.interpolate.interp1d([.7, .4], [10, 20])(.5)
'x2': 25.0, # = interp1d([.7, .3], [20, 30])(.5)
'x3': 13.3332, # = interp1d([.6, .3], [10, 20])(.5)
'x4': 20} # No interpolation required
我的数据由大约400行和50000列组成
可能的解决办法: 我发现使用以下方法查找两条直线之间的交点:
idx = np.argwhere(np.diff(np.sign(f - g)) != 0).reshape(-1) + 0
我认为这可以调整以使用我的数据帧,但我不确定如何从这里开始:
>>> idx = np.argwhere(np.diff(np.sign(df - .5), axis=0) != 0)
>>> idx
array([[1, 0],
[1, 2],
[1, 3],
[2, 1],
[2, 3]], dtype=int64)
由于人们似乎误解了这个问题,我有兴趣找到以下几点: 这可以通过线性插值两个最近的点来找到
解决方案: B.M.让我朝着正确的方向迈出了一步:
def get_intersection(df, c):
dfind = len(df) - df.loc[::-1].apply(np.searchsorted, args=(c,), raw=True)
result = {}
for i, v in enumerate(dfind):
result[df.columns.values[i]] = interp1d([df.iloc[v][i], df.iloc[v - 1][i]], [df.index[v], df.index[v - 1]])(.5)
return result
>>> get_intersection(df, .5)
{'y1': array(16.666666666666668), 'y2': array(25.0), 'y3': array(13.333333333333332), 'y4': array(20.0)}
因为您需要1D函数(interp1d),所以循环与函数一样清晰、易于阅读和速度。使用np.searchsorted查找好的段:
d = dict()
ind=df.index.values
for k,v in df.iteritems():
y=v.values
i=len(y)-np.searchsorted(y[::-1],0.5) #indices
sl = slice(i-1,i+1)
d[k]= +scipy.interpolate.interp1d(v[sl],ind[sl])(.5)
print (pd.Series(d))
# y1 16.666667
# y2 25.000000
# y3 13.333333
# y4 20.000000
# dtype: float64
如果不存在交点,可能必须调整此参数。我很困惑,您现在想从我们这里得到什么?我不确定如何使用
idx
查找ys
的值。或者,如果获取idx
的方法不必要地复杂,可以使用另一种方法计算ys
。您可以通过dfind=len(df)-df.loc[:-1]找到第一个点的索引。应用(np.searchsorted,args=(0.5,),raw=True)
。然后通过循环来完成。泰,这很有效!