1

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

netrunner
  • 45
  • 7
  • 1
    Does this answer your question? [Python - matplotlib: find intersection of lineplots](https://stackoverflow.com/questions/8094374/python-matplotlib-find-intersection-of-lineplots) – Stef Jul 01 '22 at 10:22
  • 1
    How do you come up with the points? I don't quite understand how you get the point combinations from the two lists. – moritz Jul 01 '22 at 10:33
  • @moritz `lst0` is the x index and `lst1`, `lst2` are the y indexes that share the same x values – netrunner Jul 01 '22 at 11:47
  • @Stef what if i am not allowed to use scipy – netrunner Jul 01 '22 at 11:52

1 Answers1

1

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

Stef
  • 28,728
  • 2
  • 24
  • 52
  • what if the x axis was a datetime value with `%Y-%m-%d %H:%M:%S` format, how can i perform the same calculation without converting it into an epoch number – netrunner Jul 01 '22 at 14:04