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>

<h2>Simple intuitive answer</h2>

<p>First pick the rows of interest, then average then pick the columns of interest.</p>

<pre><code>clusters_of_interest = [1, 2]
columns_of_interest = ['page']

# rows of interest
newdf = df[ df.CLUSTER.isin(clusters_of_interest) ]
# average and pick columns of interest
newdf.mean(axis=0)[ columns_of_interest ] 
</code></pre>

<h2>More advanced</h2>

<pre><code># Create groups object according to the value in the 'cluster' column
grp = df.groupby('CLUSTER')
# apply functions of interest to all cluster groupings
data_agg = grp.agg( ['mean' , 'max' , 'min' ] )
</code></pre>

<p>This is also a good <a href="http://www.shanelynn.ie/summarising-aggregation-and-grouping-data-in-python-pandas/" rel="nofollow">link</a> which describes aggregation techniques. It should be noted that the "simple answer" averages over clusters 1 AND 2 or whatever is specified in the <code>clusters_of_interest</code> while the <code>.agg</code> function averages over each group of values having the same <code>CLUSTER</code> value.</p>

python pandas numpy