netrunner
netrunner

Reputation: 55

How to find intersection points between two colums in a dataframe

How to find the intersection points in two lists of numbers that do not necessarily have any but the lines do intersect at some point

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))

the points of the first line are (1,2)(2,4) the points of the second line are (1,9)(2,1)

the intersection point should be around (0.5,3)

does pandas have anything to do so, I tried intersection but I don't think it covers my goal

Upvotes: 1

Views: 269

Answers (1)

Stef
Stef

Reputation: 30639

If lst1 and lst2 share the same x values (lst0), you can do it with simple maths: just get the slope and offset for each line segment (m and n for lst1 vs. lst0, and k and l for lst2 vs lst0, respectively). By equaling the two segment equations you get the x coords of the intersections (xs) and then from m and n the y coords:

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')

enter image description here

Upvotes: 1

Related Questions