Pandas 数据框最佳线拟合

Pandas dataframe best line fitting

您好,我有以下数据集:

A = [1,10,23,45,24,25,55,67,73,26,13,96,53,23,24,43,90, 49], 
B = [24,23,29, BW,49,59,72, BW,9,183,17,12,2,49,BW,479,18,BW]

我想在 'BW' 之间用 x 轴上的 A 列拟合直线,并将斜率值存储在新的 C 列中。 即斜率 1 是通过使用 [1,10,23] 作为 x 值和 [24,23,29] 作为 y 值获得的。斜率 2 是使用 [24,25,55] 作为 x 值和 [49,59,72] 作为 y 值获得的。这一直持续到数据帧结束。 预期输出将是:

C = [slope1, np.nan, np.nan, BW, slope2, np.nan, np.nan, BW, slope3,np.nan, np.nan,np.nan,np.nan,np.nan, BW, slope4, np.nan, BW]

此外,有没有办法在图表中显示这些线?我是新来的,不知道。非常感谢任何帮助。

您可以确定 'BW' 个位置,然后在这些索引中拆分您的数组。这是您可以执行此操作的示例:

from pprint import pprint

import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np

colors = list(mcolors.TABLEAU_COLORS.values())

A = [1, 10, 23, 45, 24, 25, 55, 67, 73, 26, 13, 96, 53, 23, 24, 43, 90, 49]
B = [24, 23, 29, 'BW', 49, 59, 72, 'BW', 9,
     183, 17, 12, 2, 49, 'BW', 479, 18, 'BW']


index = [k for k, value in enumerate(B) if value == 'BW']
index = [-1] + index + [len(B)]

slopes = []

for k in range(len(index)-1):
    x = A[index[k]+1:index[k+1]]
    y = B[index[k]+1:index[k+1]]

    if len(x) == 0:
        continue

    [slope, offset] = np.polyfit(x, y, 1)
    slopes.append(slope)

    reg_x = np.linspace(min(x), max(x), 10)
    reg_y = slope*reg_x + offset

    plt.plot(x, y, 'o', color=colors[k], label=f'Group {k}')
    plt.plot(reg_x, reg_y, color=colors[k])

pprint(slopes)

plt.legend()
plt.show()

作为斜率向量,结果是

[0.24386920980926416,
 0.5977443609022566,
 -0.9183274470232099,
 -9.808510638297868]

剧情:

也许这不是解决这个问题的最优雅或 pythonic 的方法,但可以完成工作