How to filter a dataframe based on the slope of a line between two columns

Viewed 177

I have some data I want to filter, but I can't figure out how.

I created the following plot based on my data via pandas, matplotlib, and seaborn.

enter image description here

from the following code

ax = sns.scatterplot("inverse_docking_score","MW",hue="QPlogPoct",data=df1)

sns.lineplot(data=slope_data, x="X", y="Y")

'slope_data' is just the two points you see (10.5, 300) to (12.0, 450)

I would like to make a dataframe from df1 that has all the data below the slope of this line. But I can't figure out how to do that, or what good search terms for my problem is. I've mostly found a lot of very intricate examples that are very hard to follow. I feel like this is probably a super common situation with a very easy solution I can't figure it out.

1 Answers

This is simple math. Calculate the parameters of the line (slope and intercept) and check whether the points are above or below:

# dummy data
df = pd.DataFrame({'MW': np.random.random(size=100)*250+300,
                   'score': np.random.random(size=100)*3+10
                  })

ax = sns.scatterplot(data=df, x='score', y='MW')
x1, y1 = 10,300
x2, y2 = 12,450
ax.plot((x1, x2), (y1, y2))

slope = (y2-y1)/(x2-x1)
intercept = y1-slope*x1

df2 = df[df['MW'] < df['score']*slope+intercept]
sns.scatterplot(data=df2, x='score', y='MW', marker='^', ax=ax)

points below line

Related