Pandas Mean for Certain Column
<p>I have a pandas dataframe like that:</p>

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

<p>How can I able to calculate mean (min/max, median) for specific column if Cluster==1 or CLuster==2?</p>

<p>Thanks!</p>

<p>If you meant take the mean only where Cluster is 1 or 2, then the other answers here address your issue.  If you meant take a separate mean for each value of Cluster, you can use pandas' aggregation functions, including <code>groupyby</code> and <code>agg</code>:</p>

<pre><code>df.groupby("Cluster").mean()
</code></pre>

<p>is the simplest and will take means of all columns, grouped by Cluster.</p>

<pre><code>df.groupby("Cluster").agg({"duration" : np.mean}) 
</code></pre>

<p>is an example where you are taking the mean of just one specific column, grouped by cluster. You can also use <code>np.min</code>, <code>np.max</code>, <code>np.median</code>, etc.</p>

<p>The <code>groupby</code> method produces a <code>GroupBy</code> object, which is something like but not like a <code>DataFrame</code>.  Think of it as the <code>DataFrame</code> grouped, waiting for aggregation to be applied to it. The <code>GroupBy</code> object has simple built-in aggregation functions that apply to all columns (the <code>mean()</code> in the first example), and also a more general aggregation function (the <code>agg()</code> in the second example) that you can use to apply specific functions in a variety of ways.  One way of using it is passing a <code>dict</code> of column names keyed to functions, so specific functions can be applied to specific columns.</p>

python pandas numpy