【问题标题】:Pandas dataframe best line fitting熊猫数据框最佳线拟合
【发布时间】:2021-12-22 15:07:41
【问题描述】:

您好,我有以下数据集:

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 值获得。使用 [24,25,55] 作为 x 值和 [49,59,72] 作为 y 值获得斜率 2。这一直持续到数据帧结束。 预期输出将是:

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 是什么意思?此外,您可能需要重新表述您的问题,以便更容易理解。
  • 我的意思是 B 列中出现某些文本“BW”之间的值

标签: python pandas dataframe seaborn curve-fitting


【解决方案1】:

您可以识别“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 的方法,但可以完成工作

【讨论】:

  • 是否有可能在每种情况下都有拟合优度 (R2) 值?
  • 是的,当然。在循环内部,x 和 y 数据已经分块分离,因此您可以使用 scipy 函数进行线性回归scipy.stats.linregress,它已经返回相关系数。
  • 非常感谢。这为我解决了两个月之久的问题。
猜你喜欢
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 2022-01-21
  • 2016-10-03
  • 2013-09-26
  • 1970-01-01
  • 2018-09-09
  • 2017-09-15
相关资源
最近更新 更多