繁体   English   中英

如何在数据框中找到两个列之间的交点

[英]How to find intersection points between two colums in a dataframe

如何在两个不一定有但线在某个点相交的数字列表中找到交点

lst0 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
lst1 = [2,4,1,4,1,5,7,8,3,2,4,7,8,2,1]
lst2 = [9,1,3,7,8,2,0,1,2,5,9,3,5,2,6]


data = {"index":lst0,
        "list1":lst1,
        "list2":lst2}

df = pd.DataFrame(data)
print (df.head(5))

第一行的点是 (1,2)(2,4) 第二行的点是 (1,9)(2,1)

交点应该在 (0.5,3) 附近

熊猫有什么关系吗,我尝试过交集,但我认为它不能涵盖我的目标

如果lst1lst2共享相同的 x 值( lst0 ),您可以通过简单的数学计算:只需获取每个线段的斜率和偏移量( lst1lst0mnlst2lst0kl ,分别)。 通过等于两个线段方程,您可以得到交叉点 ( xs ) 的x坐标,然后从mn得到y坐标:

import pandas as pd
import numpy as np

lst0 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
lst1 = [2,4,1,4,1,5,7,8,3,2,4,7,8,2,1]
lst2 = [9,1,3,7,8,2,0,1,2,5,9,3,5,2,6]
data = {"index":lst0,
        "list1":lst1,
        "list2":lst2}
df = pd.DataFrame(data)

x = df['index'].to_numpy()
y = df.list1.to_numpy()
z = df.list2.to_numpy()

# slopes and offsets lst1 vs lst0
m = np.diff(y)/np.diff(x)
n = y[1:] - m * x[1:]

# slopes and offsets lst2 vs lst0
k = np.diff(z)/np.diff(x)
l = z[1:] - k * x[1:]

# intersections
with np.errstate(divide='ignore'):
    xs = (n - l) / (k - m)
    ys = m * xs + n

# only take intersections that lie in the respective segment
mask = (xs >= x[:-1]) & (xs <= x[1:])
intersections = np.unique(np.row_stack((xs[mask], ys[mask])), axis=1)

# display result
ax = df.set_index('index').plot(legend=False)
ax.plot(intersections[0], intersections[1], 'ro')

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM