Python Forum
how to fit an exponential function to multiple data - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: how to fit an exponential function to multiple data (/thread-21258.html)



how to fit an exponential function to multiple data - python_newbie09 - Sep-21-2019

I would like to fit an exponential function based on data points of more than one trend. Is this possible?
The code below creates a fit for every column in the table but if I want to group these columns according to a certain criteria so say the points in column A, B and C needs to learn the same exponential fit, i am not very sure how to do incorporate that requirement here. Thanks.

# Initial parameter guess, just to kick off the optimization
init = (0.1, 0.1)

# Place to store function parameters for each column
col_params = {}

def func(x, a, b):
    return a*np.exp(-b*x)

# Curve fit each column
for col in df.columns:
    # Get x & y
    x = df.index.astype(float).values
    y = df[col].values
    
    # Curve fit column and get curve parameters
    params = curve_fit(func, x, y, init)
      
    # Store optimized parameters
     col_params[col] = params[0]
        

# Extrapolate each column
for col in df.columns:
    # Get the index values for NaNsY in the column
    x = df[pd.isnull(df[col])].index.astype(float).values 
    y = df[col].values

    # Extrapolate those points with the fitted function
    df[col][x] = func(x, *col_params[col])
    plt.plot(x1,y,func(x, *col_params[col]),'g--')
            



RE: how to fit an exponential function to multiple data - scidam - Sep-24-2019

Not sure about what you are trying to get, but take a look at RANSAC algorithm. It allows to find the best fit, as if A, B and C in your case were undistinguished. There is a Python implementation of RANSAC. However, it uses a while loop when finding the best combination, so, it would be probably better (more efficient) to rewrite all code using Cython (or C).