【发布时间】:2020-08-02 20:24:41
【问题描述】:
我有一个包含四列的数据集:处理 (hr)、时间 (t)、自变量 (y) 和标准偏差 (s_y)。治疗包括2组,A和B。
我已经定义了一个函数(模型),我想将它拟合到我的数据(y)中。我想将该功能应用于列处理下的组。我考虑过使用“groupby”根据治疗对 y 进行分组。但是,我的函数需要一个参数,K,它是基于 index 定义的。例如,它必须对应于 y 列表中的第三个值。由于我想根据治疗创建子组,我应该为每个子组获得不同的 K。我无法将 reset.index() 选项应用于 groupby,所以我不知道如何告诉我的函数为每个子组获取 y 的第三个值。
有没有更有效的方法来循环处理不同组的函数?
这是代码:
this is my df:
treatment time y std_y
A 1 2.29 0.30
A 2 2.68 0.29
A 3 2.79 0.29
B 1 2.25 0.07
B 2 2.53 0.07
B 3 2.55 0.07
for i, g in df.groupby('treatment'):
def model (t, m, B, n):
k = 0.2
return K*np.exp(-m*t) + B*np.exp(-n*t)
# k is the parameter that I would like to define based on index for each group in treatment.
# It has to correspond to the 3rd element of y, and it should be a different value for group (A and B).
fit = curve_fit(model, g['time'], g['y'],
sigma=g['std_y'],
p0=None)
ans,cov = fit
fit_m, fit_B, fit_n = ans
【问题讨论】:
-
第 3 个元素用于示例(表示组中的最后一行)或
k始终是第 3 个元素,无论组的形状如何? -
K 将始终是第三个元素,无论组的形状如何。谢谢
标签: loops indexing pandas-groupby rows