value counts of group by in pandas
<p>I am new to pandas and was trying to learn about this feature.</p>

<pre><code>iris = datasets.load_iris()
grps = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
iris = pd.DataFrame(iris.data[:,0],columns = ["SL"])
iris['bins'] = pd.cut(iris["SL"], 10 ,labels = grps )
iris['target'] = datasets.load_iris().target
</code></pre>

<p>I would like to have the number of occurence of each class in each bins. How do i do this as i cannot seem to think of a way. And i would like to plot this output as a stacked histogram</p>

<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a> after you have binned them into bins corresponding to the groups specified in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>cut</code></a>.</p>

<pre><code>sns.set_style('darkgrid')

df = pd.DataFrame(datasets.load_iris().data[:,0], columns=['SL'])
df['target'] = datasets.load_iris().target

# Total number of bins to be grouped under
grps = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Empty list to append later
grouped_list = []

# Iterating through grouped by target variable
for label, key in df.groupby('target'):
    grouped_list.append(pd.cut(key['SL'], bins = grps).value_counts())

# Concatenate column-wise and create a stacked-bar plot
pd.concat(grouped_list, axis=1).add_prefix('class_').plot(kind='bar', stacked=True, rot=0, 
                                                        figsize=(6,6), cmap=plt.cm.rainbow)

# Aesthetics
plt.title("Sepal Length binned counts")
plt.xlabel("Buckets")
plt.ylabel("Occurences")
sns.plt.show()
</code></pre>

<p><a href="http://i.stack.imgur.com/itYfa.png" rel="nofollow"><img src="http://i.stack.imgur.com/itYfa.png" alt="Image"></a></p>

python pandas matplotlib dataframe