【发布时间】:2016-03-24 12:06:24
【问题描述】:
我正在尝试确定两条线的交点。
蓝线是我的y变量,由df['Amount']/df['SomeNumber']计算得出。
绿线由 2 个x_coords 和 2 个y_coords(坐标)创建,斜率为115.38461538461503,截距为-74.076923076922739。
>>> x_coords
[0.84999999999999998, 0.97999999999999998]
>>> y_coords
[24, 39]
建议 scipy.optimize、fsolve 或 numpy 的 polyfit,但到目前为止我都没有成功。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'SomeNumber': [0.85, 0.98, 1.06, 1.1, 1.13, 1.2, 1.22, 1.23, 1.31, 1.43],
'Events': [24, 39, 20, 28, 20, 24, 26, 29, 30, 24],
'Amount': [35.78, 35.78, 35.78, 35.78, 35.78, 35.78, 35.78, 35.78, 35.78, 35.78]},
columns=['Amount', 'Events', 'SomeNumber'])
df = df.sort('SomeNumber')
x = df['SomeNumber']
y = df['Amount']/df['SomeNumber']
df_below = df[df['Events'] < y]
df_above = df[df['Events'] >= y]
x_coords = [df_below['SomeNumber'].min(), df_above['SomeNumber'].min()]
y_coords = [df_below.ix[df_below['SomeNumber'].idxmin(), 'Events'],
df_above.ix[df_above['SomeNumber'].idxmin(), 'Events']]
slope, intercept = np.polyfit(x_coords, y_coords, 1)
#>>> slope, intercept == (115.38461538461503, -74.076923076922739)
plt.plot(x, y, label='Potential Events')
plt.scatter(x, df['Events'], label='Actual Events')
plt.plot(x_coords, y_coords)
plt.xlabel('Some Number')
plt.ylabel('Events')
plt.legend(loc='upper right')
plt.show()
【问题讨论】:
-
This 可能会有所帮助。
标签: python numpy pandas matplotlib scipy