首页 \ 问答 \ 在数据框列上应用curve_fit(Apply curve_fit on dataframe columns)

在数据框列上应用curve_fit(Apply curve_fit on dataframe columns)

我有一个带有多列的pandas.DataFrame ,我想对每个列应用一个curve_fit函数。 我希望输出是一个数据框,其最佳值适合列中的数据(目前,我对它们的协方差不感兴趣)。

df具有以下结构:

    a  b  c
0   0  0  0
1   0  0  0
2   0  0  0
3   0  0  0
4   0  0  0
5   0  0  0
6   1  0  1
7   1  1  1
8   1  1  1
9   1  1  1
10  1  1  1
11  1  1  1
12  1  1  1
13  1  1  1
14  2  1  2
15  6  2  6
16  7  2  7
17  8  2  8
18  9  2  9
19  7  2  7

我已经定义了一个适合数据的函数,如下所示:

def sigmoid(x, a, x0, k):
     y = a / (1 + np.exp(-k*(x-x0)))
     return y

def fitdata(dataseries):
    popt, pcov=curve_fit(sigmoid, dataseries.index, dataseries)
    return popt

我可以应用该函数并获得一个数组作为回报:

result_a=fitdata(df['a'])
In []: result_a
Out[]: array([  8.04197008,  14.48710063,   1.51668241])

如果我尝试df.apply函数我得到以下错误:

fittings=df.apply(fitdata)
ValueError: Shape of passed values is (3, 3), indices imply (3, 20)

最终我希望输出看起来像:

           a          b          c
0   8.041970   2.366496   8.041970
1  14.487101  12.006009  14.487101
2   1.516682   0.282359   1.516682

这可以用类似的东西来完成吗?


I have a pandas.DataFrame with with multiple columns and I would like to apply a curve_fit function to each of them. I would like the output to be a dataframe with the optimal values fitting the data in the columns (for now, I am not interested in their covariance).

The df has the following structure:

    a  b  c
0   0  0  0
1   0  0  0
2   0  0  0
3   0  0  0
4   0  0  0
5   0  0  0
6   1  0  1
7   1  1  1
8   1  1  1
9   1  1  1
10  1  1  1
11  1  1  1
12  1  1  1
13  1  1  1
14  2  1  2
15  6  2  6
16  7  2  7
17  8  2  8
18  9  2  9
19  7  2  7

I have defined a function to fit to the data as so:

def sigmoid(x, a, x0, k):
     y = a / (1 + np.exp(-k*(x-x0)))
     return y

def fitdata(dataseries):
    popt, pcov=curve_fit(sigmoid, dataseries.index, dataseries)
    return popt

I can apply the function and get an array in return:

result_a=fitdata(df['a'])
In []: result_a
Out[]: array([  8.04197008,  14.48710063,   1.51668241])

If I try to df.apply the function I get the following error:

fittings=df.apply(fitdata)
ValueError: Shape of passed values is (3, 3), indices imply (3, 20)

Ultimately I would like the output to look like:

           a          b          c
0   8.041970   2.366496   8.041970
1  14.487101  12.006009  14.487101
2   1.516682   0.282359   1.516682

Can this be done with something similar to apply?

更新时间:2023-02-03 16:02

最满意答案

希望我的解决方案能为您服务。

result = pd.DataFrame()
for i in df.columns:
    frames = [result, pd.DataFrame(fitdata(df[i]))]
    result = pd.concat(frames, axis=1)
result.columns = df.columns

           a           b           c
0   8.041970    2.366496    8.041970
1   14.487101   12.006009   14.487101
2   1.516682    0.282359    1.516682

Hope my solution work for you.

result = pd.DataFrame()
for i in df.columns:
    frames = [result, pd.DataFrame(fitdata(df[i]))]
    result = pd.concat(frames, axis=1)
result.columns = df.columns

           a           b           c
0   8.041970    2.366496    8.041970
1   14.487101   12.006009   14.487101
2   1.516682    0.282359    1.516682

相关问答

更多
  • 将x和y更改为numpy数组 x = np.array([40,45,50,55,60]) y = np.array([0.99358851674641158, 0.79779904306220106, 0.60200956937799055, 0.49521531100478472, 0.38842105263157894]) 然后我觉得你很好,因为这个函数需要矢量化计算,而列表则不够。 change x and y to numpy arrays x = np.array([40,45,50,55,6 ...
  • 已经指出了代码的一些问题。 这是一个解决方案: 首先,您需要获得原始函数的正确对数表达式: y = 1 / (c * exp(-b * x)) y = exp(b * x) / c ln(y) = b * x + ln(1/c) ln(y) = b * x - ln(c) 如果要在curve_fit使用它, curve_fit需要按如下方式定义函数: def f_log(x, b, c_ln): return b * x - c_ln 我现在向您展示一些随机生成的数据(使用b = 0.08和c ...
  • scipy.optimize.leastsq不支持边界,并且由curve_fit直到scipy版本0.17。 OTOH, scipy.optimize.least_squares (在更新版本的scipy中由curve_fit使用)可以支持边界,但不能在使用lm (Levenberg-Marquardt)方法时使用,因为这是scipy.optimize.leastsq的简单包装。 这有点令人困惑。 请允许我建议尝试lmfit ( http://lmfit.github.io/lmfit-py/ ),它支持所 ...
  • 好的,两个有用的技巧。 1,用你的x代替0 ,然后用一些非常小的数字代替,比如1e-8 (不要笑,在R有一个核心包,实际上这个是用his name shall not be spoken写的his name shall not be spoken ,人们his name shall not be spoken用它)其实我没有得到你的RuntimeWarning 。 我运行scipy 0.12.0和numpy 1.7.1 。 也许这是版本依赖。 但我们会遇到一个非常糟糕的情况: In [41]: popt, ...
  • 不使用curve_fit另一种方法是使用numpy的polyfit 。 import matplotlib.pyplot as plt import numpy as np # This is merely a sample of some of my actual data x = [290., 300., 310.] y = [1.87e+21, 2.07e+21, 2.29e+21] xp = np.linspace(290, 310, 100) z = np.polyfit(x, y, 1) ...
  • 您可能会发现lmfit模块( https://lmfit.github.io/lmfit-py/ )对此非常有用。 它旨在使曲线拟合非常容易,具有高斯等常见峰值的内置模型,并具有许多有用的功能,例如允许您设置参数的界限。 使用lmfit适合您的数据可能如下所示: import numpy as np import matplotlib.pyplot as plt from lmfit.models import GaussianModel, ConstantModel y = np.array([... ...
  • 作为回溯状态,达到了最大数量的功能评估,但没有找到稳定点(终止算法)。 您可以使用选项maxfev增加最大数量。 对于这个例子,设置maxfev=2000足够大,可以成功终止算法。 但是,解决方案并不令人满意。 这是由于算法选择变量的(默认)初始估计,对于这个例子,这是不好的(所需的大量迭代是这个的指示)。 提供另一个初始化点(通过简单的试验和错误找到)可以很好地适应,而不需要增加maxfev 。 下面显示了两种拟合和与数据的视觉比较。 x = np.asarray([ 1000, 3250, 5500, ...
  • 希望我的解决方案能为您服务。 result = pd.DataFrame() for i in df.columns: frames = [result, pd.DataFrame(fitdata(df[i]))] result = pd.concat(frames, axis=1) result.columns = df.columns a b c 0 8.041970 2.366496 8.041970 1 ...
  • 这不是一个数字问题。 “问题”是协方差矩阵的非对角线项都是正的且相对较大。 这些确定了拟合中误差之间的相关性,因此如果所有术语都是正数,则表示所有误差都是正相关的。 如果一个人很大,那么其他人也会因为同一个标志而变大。 这是一个类似于你的例子,带有协方差矩阵 [2.0 1.3 0.0] sigma = [1.3 2.0 1.3] [0.0 1.3 2.0] (该矩阵的条件数为23.76,因此我们不应期望任何数值问题。) 虽然第一点和第三点之间的协方差是0,但是在 ...
  • 我看到两个问题: 在fitfunc你写 tempArray[time <= 0] = line(time, p[6]) tempArray[0 < time] = exponential(time, p[0], p[1], p[2]) + exponential(time, p[3], p[4], p[5]) 但是在均等的两边,阵列的大小并不相同。 我认为在第二行时代并不好; 我用它替换了它 tempArray[time <= 0] = line(time[time<=0], p[6]) ...

相关文章

更多

最新问答

更多
  • 在csproj中使用appdata环境变量(Use appdata environment variable in csproj)
  • 从背景返回后,Skobbler Map崩溃(Skobbler Map crashes after returning from background)
  • 如何保持对绑定服务的轮询?(How to keep polling a bound service?)
  • ASP.NET单选按钮jQuery处理(ASP.NET radio button jQuery handling)
  • Linux上的FORTRAN图形库(FORTRAN graphic library on Linux)
  • 我们如何根据索引更新dynamodb表(不基于primary has和range key)(how can we update dynamodb table based on index(not based on primary has and range key))
  • 功能包装避免重复(wrap of functions avoid duplicating)
  • Android BroadcastReceiver和Activity.onPause()(Android BroadcastReceiver and Activity.onPause())
  • 无法使用phonegap 2.4在Android上播放录音(unable to play audio recordings on android using phonegap 2.4)
  • VS2015 + Resharper:不要使用C#6(VS2015 + Resharper: Don't use C#6)
  • 大学电脑四级对初学者来说要多久能过
  • 特殊字符删除?(Special characters remove?)
  • Android视频教程现在网上的都比较零散呢?有些太坑爹了,感觉老师就是在想当然的讲
  • 计算同一个表中不同行之间的差异[重复](Calculate delta's between different rows in same table [duplicate])
  • Javaweb开发,技术路线是什么?该怎么写?
  • JavaScript只在php代码中执行一次(JavaScript only executes once inside php code)
  • 不兼容的字符编码:ASCII-8BIT和UTF-8(incompatible character encodings: ASCII-8BIT and UTF-8)
  • Clojure(加载文件)给出错误(Clojure (load-file) gives an error)
  • 为具有瞬态scala依赖性的spring-xd项目优化gradle(Optimize gradle for spring-xd project with transient scala dependency)
  • 如何才能在Alpha测试模式下发布我的应用程序?(How can I publish my app in Alpha test mode only?)
  • “没有为此目标安装系统映像”Xamarin AVD Manager(“No system images installed for this target” Xamarin AVD Manager)
  • maven中的Scalatest:JUnit结果(Scalatest in maven: JUnit results)
  • 使用android SDK将文件直接上传到存储桶中的文件夹(Upload a file directly to a folder in bucket using android SDK)
  • 是否应将plists导入CoreData?(Should plists be imported to CoreData?)
  • java.lang.reflect.InvocationTargetException JavaFX TableView(java.lang.reflect.InvocationTargetException JavaFX TableView)
  • 根据唯一列值动态创建多个子集(Dynamically create multiple subsets based on unique column values)
  • 使用CSS可以使HTML锚标签不可点击/可链接吗?(Is it possible to make an HTML anchor tag not clickable/linkable using CSS?)
  • 嵌套的模板可能性(Nested template possibilities)
  • 任何方式在iOS7 +上以编程方式打开蓝牙(Any way to turn on bluetooth programmatically on iOS7+)
  • 如何为给定的SQL查询编写JPA查询(How I can write JPA query for given SQL query)