【问题标题】:How to pass a pandas dataframe to `scipy.optimize.curve_fit` or `scipy.stats.linregress`如何将熊猫数据框传递给`scipy.optimize.curve_fit`或`scipy.stats.linregress`
【发布时间】:2018-11-20 16:52:27
【问题描述】:

这里有类似的问题:Pass Pandas DataFrame to Scipy.optimize.curve_fit

我现在有一个 shape=(100, 4) 的数据框,即四个从属变量 Y1 到 Y4。使用另一个独立数组 m = [1, 2, 3, 4]。我需要用 Ys 和 m 建立一个线性模型,生成一个预测的 Y 值。

如何为整个数据框执行此操作,而不是在 for 循环中对数据框的每一行执行此操作?

import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
from scipy.stats import linregress

Y = np.random.randn(100, 4) 
m = np.array([1, 2, 3, 4])    

df = pd.DataFrame(Y, columns=['y1', 'y2', 'y3', 'y4'])
for index, row in df.iterrows():
    slope, intercept, r_value, p_value, std_err = linregress(m, row.values)
    print(slope, intercept)

【问题讨论】:

  • "但它对我不太有效" 究竟是什么?您能否详细说明(意外结果、错误……)?!
  • .values 是从数据帧中获取 numpy 数组的常用方法。
  • @Cleb 嗨,我已更改代码以显示我尝试过的内容,对每一行使用 for 循环。

标签: python pandas scipy


【解决方案1】:

首先,最好使用对行的观察来格式化数据。也就是说,每个观察都由其他列中的维度(变量(x1-4))描述。之后,您可以将解释变量与响应 (y) 一起传递给模型函数,响应可以是数据框的一列,也可以是外部但具有相同的行数。

显然,linregress 函数仅将单个解释变量拟合到响应变量上。

对于 >2 维建模,我建议使用其他软件包,例如 statsmodels 或 sklearn.linear_model.LinearRegression

下面我继续前面的建议:

import numpy as np
import pandas as pd
from statsmodels.formula.api import ols

data = np.random.randn(100, 4)
y = np.random.randn(100)
df = pd.DataFrame(data, columns=['x1', 'x2', 'x3', 'x4'])

x1 = df['x1']
x2 = df['x2']
x3 = df['x3']
x4 = df['x4']

model = ols("y ~ x1 + x2 + x3 + x4", df).fit()
print(model.summary())

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 2015-01-13
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多