Find Rolling Mean – Python Pandas

PythonServer Side ProgrammingProgramming

<p>To find rolling mean, we will use the apply() function in Pandas. At first, let us import the required library &minus;</p><pre class="just-code notranslate language-python" data-lang="python">import pandas as pd</pre><p>Create a DataFrame with 2 columns. One is an int column &minus;</p><pre class="just-code notranslate language-python" data-lang="python" style="">dataFrame = pd.DataFrame( &nbsp; &nbsp;{ &nbsp; &nbsp; &nbsp; &quot;Car&quot;: [&#39;Tesla&#39;, &#39;Mercedes&#39;, &#39;Tesla&#39;, &#39;Mustang&#39;, &#39;Mercedes&#39;, &#39;Mustang&#39;], &nbsp; &nbsp; &nbsp; &quot;Reg_Price&quot;: [5000, 1500, 6500, 8000, 9000, 6000] &nbsp; &nbsp;} )</pre><p>Group using GroupBy and find the Rolling Mean using apply() &minus;</p><pre class="just-code notranslate language-python" data-lang="python" style="">dataFrame.groupby(&quot;Car&quot;)[&quot;Reg_Price&quot;].apply( lambda x: x.rolling(center=False, window=2).mean()) </pre><h2>Example</h2><p>Following is the code &minus;</p><pre class="demo-code notranslate language-python" data-lang="python" style="">import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { &quot;Car&quot;: [&#39;Tesla&#39;, &#39;Mercedes&#39;, &#39;Tesla&#39;, &#39;Mustang&#39;, &#39;Mercedes&#39;, &#39;Mustang&#39;], &quot;Reg_Price&quot;: [5000, 1500, 6500, 8000, 9000, 6000] } ) print&quot;DataFrame ... &quot;,dataFrame print&quot; Rolling Mean... &quot;,dataFrame.groupby(&quot;Car&quot;)[&quot;Reg_Price&quot;].apply( lambda x: x.rolling(center=False, window=2).mean()) </pre><h2 style="">Output</h2><p>This will produce the following output &minus;</p><pre class="result notranslate">DataFrame ... &nbsp; &nbsp; &nbsp; &nbsp; Car &nbsp; Reg_Price 0 &nbsp; &nbsp; Tesla &nbsp; &nbsp; &nbsp; 5000 1 &nbsp;Mercedes &nbsp; &nbsp; &nbsp; 1500 2 &nbsp; &nbsp; Tesla &nbsp; &nbsp; &nbsp; 6500 3 &nbsp; Mustang &nbsp; &nbsp; &nbsp; 8000 4 &nbsp;Mercedes &nbsp; &nbsp; 9000 5 &nbsp; Mustang 6000 Rolling Mean... 0 NaN 1 NaN 2 5750.0 3 NaN 4 5250.0 5 7000.0 Name: Reg_Price, dtype: float64</pre>
raja
Updated on 17-Sep-2021 07:30:12

Advertisements