'Generating a Non Linear equation in Python like an excel output
I have some sample data below:
Freemium: 0.5, 0.3333 , 0.1666, 0.0466, 0.0466, 0.1, 0.1666,
0.3333, 0.5
Minutes:0, 60, 120 ,180 ,240 ,300 ,360 ,420, 480
I want to use to data to build a Non-Linear equation where Minutes is x and Freemium is the y.
Just as a reference equation I used the same data in excel to create a Non- Linear equation for Minutes and Freemium and excel made the equation look like this:
y = -0.000000000000001561203414339570x6 + 0.000000000002445980336850290000x5 - 0.000000001484771616406030000000x4 + 0.000000431626331238999000000000x3 - 0.000050863545408175200000000000x2 - 0.000887445386510421000000000000x + 0.499125614496862000000000000000
I want to use python (preferably pandas) to build a Non Linear equation that prints like the excel above with the data I have in the table.
Solution 1:[1]
You can do that with polyfit from the Numpy library. Formatting the equation nicely takes a couple lines of code. You can change the loop to match your preferred format.
import numpy as np
minutes = [0, 60, 120, 180, 240, 300, 360, 420, 480]
freemium = [0.5, 0.3333, 0.1666, 0.0466, 0.0466, 0.1, 0.1666, 0.3333, 0.5]
degree = 6
coefficients = np.polyfit(minutes, freemium, degree)
equation = "y = "
for i, coeff in enumerate(coefficients):
power = degree - i
if power < degree:
equation += " + "
equation += str(coeff)
if power == 1:
equation += " x"
elif power > 1:
equation += f" x^{power}"
print(equation)
prints
y = -1.562261850327855e-15 x^6 + 2.4477517938168308e-12 x^5 + -1.4858670992931515e-09 x^4 + 4.319296328671704e-07 x^3 + -5.089791979625905e-05 x^2 + -0.0008867371406366774 x + 0.49912484848483274
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |