Find linear part and slope in curve
<p>For a device that monitors the mass change in function of time, we would like to calculate the slope of the linear part of the data.</p>

<p>The example shown below is produced by reading a dataframe produced by the device.</p>

<pre><code>import pandas as pd
import matplotlib.pyplot as plt

#Find DataFrame
df = pd.read_table("raw_data.csv", sep =";", skiprows = 11, decimal = ",")

# Plot figures
plt.figure()
plt.plot(df["Time(s)"], df["Mass(g)"], label = "Raw Data")
plt.axvspan(2, 17, color="b", alpha=0.2)
plt.xlabel("Time (s)")
plt.ylabel("Mass (g)")
plt.legend(loc=0)
plt.axis([0, None, 0, None])
plt.show()
</code></pre>

<p><img src="http://i.stack.imgur.com/fJZXs.png" alt="Example curve"></p>

<p>Is it possible to fit the linear part in this curve (roughly the highlighted part) and calculate the slope of it?</p>

<p>Use <strong>numpy.polyfit()</strong> :</p>

<pre><code>df_sampled = df[:max_value] #select the points you want to keep
m, p = numpy.polyfit(df_sampled.index, df_sampled, deg=1)
</code></pre>

<p>The function returns the <strong>slope</strong> and the <strong>intercept</strong> of your linear regression.</p>

python pandas plot dataframe