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>You can do it in one line, using <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">boolean indexing</a>. For example you can do something like:</p>

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

# This will just produce an example DataFrame
df = pd.DataFrame({'a':np.arange(30), 'Cluster':np.ones(30,dtype=np.int)})
df.loc[10:19, "Cluster"] *= 2
df.loc[20:,   "Cluster"] *= 3

# This line is all you need
df.loc[(df['Cluster']==1)|(df['Cluster']==2), 'a'].mean()
</code></pre>

<p>The boolean indexing array is <code>True</code> for the correct clusters. <code>a</code> is just the name of the column to compute the mean over.</p>

python pandas numpy