How to get mean of rows selected with another column's values in pandas
<p>I am trying to get calculate the mean for Score 1 only if column <code>Dates</code> is equal to <code>Oct-16</code>:</p>

<p><a href="https://i.stack.imgur.com/PR8jf.png" rel="nofollow"><img src="https://i.stack.imgur.com/PR8jf.png" alt="enter image description here"></a></p>

<p>What I originally tried was:</p>

<pre><code> import pandas as pd
 import numpy as np
 import os

 dataFrame = pd.read_csv("test.csv")

 for date in dataFrame["Dates"]:
    if date == "Oct-16":
        print(date)##Just checking
        print(dataFrame["Score 1"].mean())
</code></pre>

<p>But my results are the mean for the whole column <code>Score 1</code></p>

<p>Another thing I tried was manually telling it which indices to calculate the mean for:</p>

<pre><code>dataFrame["Score 1"].iloc[0:2].mean()
</code></pre>

<p>But ideally I would like to find a way to do it if <code>Dates == "Oct-16"</code>.</p>

<p>Iterating through the rows doesn't take advantage of Pandas' strengths.  If you want to do something with a column based on values of another column, you can use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>.loc[]</code></a>:</p>

<pre><code>dataFrame.loc[dataFrame['Dates'] == 'Oct-16', 'Score 1']
</code></pre>

<p>The first part of <code>.loc[]</code> selects the rows you want, using your specified criteria (<code>dataFrame['Dates'] == 'Oct-16'</code>).  The second part specifies the column you want (<code>Score 1</code>).  Then if you want to get the mean, you can just put <code>.mean()</code> on the end:</p>

<pre><code>dataFrame.loc[dataFrame['Dates'] == 'Oct-16', 'Score 1'].mean()
</code></pre>

python pandas numpy